jQuery ( function () {
	initOpenClose ();
	initCustomForm ();
})

function initNews () 
{	
	jQuery(document).ready(function() 
	{
		jQuery('#news-list').newsTicker({
			'items'		: 3,
			'interval'	: 5000,
			'slideSpeed': 500
		});
	});
}

// initCustomForm
function initCustomForm () {
	jQuery ( 'select' ).customSelect ();
	//jQuery ( 'input:radio' ).customRadio ();
	jQuery ( 'input:checkbox' ).customCheckbox ();
}

// initOpenClose
function initOpenClose () {
	var _btn = jQuery ( '.content-view' ),
		_window = jQuery ( 'body' );
	
	_btn.click ( function () {
		_window.toggleClass ( 'hidden-content' );
		
		/*
		var imgHeight = jQuery( "#background img" ).height();
		jQuery( '#background' ).css( 'position', 'absolute' );
		jQuery( '#background img' ).css( 'position', 'absolute' );
		jQuery( "#container" ).css( 'height', imgHeight );
		//console.log(  );
		*/
		return false;
	})
}

// custom forms plugin
;(function($){
	
	/* BEGIN NEWSTICKER PLUGIN */
	$.fn.newsTicker = function( settings )
	{
		var el = this;
		var lastChange = $(this).attr('class').split( "_" )[1];
		
		this.init = function ()
		{
			// init settings
			var defaultSettings = {
				'items' 	: 3,
				'interval' 	: 2000,
				'slideSpeed': 500
			};
			
			if ( !settings ) settings = defaultSettings;
			else
			{
				for ( var sName in settings )
					if ( defaultSettings[sName] )
						defaultSettings[sName] = settings[sName];
				
				settings = defaultSettings;
			}
			
			// init element
			var curListItems 	= el.children();
			var displayHeight 	= 0;
			
			for ( i=0; i<settings.items; i++ )
				displayHeight += $( curListItems[i] ).outerHeight();
			
			el.css( 'overflow', 'hidden' );
			el.css( 'height', displayHeight + 'px' );
		}
		
		this.slideNext = function ()
		{
			var topItem = $( 'li:first-child', el );
			var topItemMarginBefore = topItem.css( 'marginTop' );
			var nextItem = $( 'li:nth-child('+(settings.items+1)+')', el);
			
			// animate top item position
			topItem.animate(
				{'margin-top': '-' + topItem.outerHeight() + 'px'}, 
				settings.slideSpeed, 
				function ()
				{
					topItem.css( 'margin-top', topItemMarginBefore );
					
					if ( $(this).hasClass('remove-item') ) $(this).remove();
					else $(el).append( $(this) );
				}
			);
			
			// animate outside container height
			el.animate(
				{ 'height': (el.height() + (nextItem.outerHeight()-topItem.outerHeight())) + 'px' },
				settings.slideSpeed
			);
			
			// set new interval
			slideInterval = setTimeout( function () { el.slideNext() }, settings.interval );
		}
		
		this.checkNews = function ( lastChange )
		{
			jQuery.getJSON( '/?eID=ajax&action=getNews', function (data) 
			{ 
				// we'll check again in 15 secs
				updateInterval = setTimeout( function () { el.checkNews( data.lastChange ) }, 15000 );
				
				// check for change, or stop
				if ( data.lastChange <= lastChange ) return;
				
				// stop slide interval while updating
				window.clearTimeout( slideInterval );
				
				// generate new items
				var newListHtml = '';
				for ( i=0; i<data.items.length; i++ )
				{
					//newListItems[ data.items[i].id ] = data.items[i];
					var newItem 	= data.items[i];
					var date 		= new Date( newItem.datetime );
					var months 		= ['January','February','March','April','May','June','July','August','September','October','November','December'];
					var newItemHtml = '<li id="' +  newItem.id + '">'
									+ '<p>' 
									+  newItem.headline 
									+ ' &dash; '
									+ '<strong>' + newItem.dateline 
									+ '</strong>'
									+ '</p>'
									+ '<em class="date">'
									+ months[ date.getMonth() ] + ', ' + date.getDay() + ' ' + date.getHours() + ':' + date.getMinutes()
									+ ' '
									+ newItem.copyrightline
									+ '</em>'
									+ '</li>';
					newListHtml += newItemHtml;
				}
				
				// remove non visible items
				var currentChildren = $(el).children();
				for ( i=0; i<currentChildren.length-settings.items-1; i++ )
					$(currentChildren[i+settings.items+1]).remove();
					
				// mark old items for removal
				$( 'li', el).addClass( 'remove-item' );
				
				// append new items to list
				$(el).append( newListHtml );
				
				// resume slide interval
				slideInterval = setTimeout( function () { el.slideNext() }, settings.interval );
			});
		}
		
		// start ticker
		this.init();
		var slideInterval = setTimeout( function () { el.slideNext() }, settings.interval );
		var updateInterval = setTimeout( function () { el.checkNews( lastChange ) }, 10000 );
	};
	/* END NEWSTICKER PLUGIN */
	
	// custom checkboxes module
	$.fn.customCheckbox = function(_options){
		var _options = $.extend({
			checkboxStructure: '<div></div>',
			checkboxDisabled: 'disabled',
			checkboxDefault: 'checkboxArea',
			checkboxChecked: 'checkboxAreaChecked'
		}, _options);
		return this.each(function(){
			var checkbox = $(this);
			if(!checkbox.hasClass('outtaHere') && checkbox.is(':checkbox')){
				var replaced = $(_options.checkboxStructure);
				this._replaced = replaced;
				if(checkbox.is(':disabled')) replaced.addClass(_options.checkboxDisabled);
				else if(checkbox.is(':checked')) replaced.addClass(_options.checkboxChecked);
				else replaced.addClass(_options.checkboxDefault);

				replaced.click(function(){
					if(checkbox.is(':checked')) checkbox.removeAttr('checked');
					else checkbox.attr('checked', 'checked');
					changeCheckbox(checkbox);
				});
				checkbox.click(function(){
					changeCheckbox(checkbox);
				});
				replaced.insertBefore(checkbox);
				checkbox.addClass('outtaHere');
			}
		});
		function changeCheckbox(_this){
			_this.change();
			if(_this.is(':checked')) _this.get(0)._replaced.removeClass().addClass(_options.checkboxChecked);
			else _this.get(0)._replaced.removeClass().addClass(_options.checkboxDefault);
			
			// submit form when permission checkbox is clicked
			if( _this.attr('id') == 'permission' ) $( _this ).parents( 'form' ).submit();
		}
	}

	// custom radios module
	$.fn.customRadio = function(_options){
		var _options = $.extend({
			radioStructure: '<div></div>',
			radioDisabled: 'disabled',
			radioDefault: 'radioArea',
			radioChecked: 'radioAreaChecked'
		}, _options);
		return this.each(function(){
			var radio = $(this);
			if(!radio.hasClass('outtaHere') && radio.is(':radio')){
				var replaced = $(_options.radioStructure);
				this._replaced = replaced;
				if(radio.is(':disabled')) replaced.addClass(_options.radioDisabled);
				else if(radio.is(':checked')) replaced.addClass(_options.radioChecked);
				else replaced.addClass(_options.radioDefault);
				replaced.click(function(){
					if($(this).hasClass(_options.radioDefault)){
						radio.attr('checked', 'checked');
						changeRadio(radio.get(0));
					}
				});
				radio.click(function(){
					changeRadio(this);
				});
				replaced.insertBefore(radio);
				radio.addClass('outtaHere');
			}
		});
		function changeRadio(_this){
			$(_this).change();
			$('input:radio[name='+$(_this).attr("name")+']').not(_this).each(function(){
				if(this._replaced && !$(this).is(':disabled')) this._replaced.removeClass().addClass(_options.radioDefault);
			});
			_this._replaced.removeClass().addClass(_options.radioChecked);
		}
	}

	// custom selects module
	$.fn.customSelect = function(_options) {
		var _options = $.extend({
			selectStructure: '<div class="selectArea"><span class="left"></span><span class="center"></span><a href="#" class="selectButton"></a><div class="disabled"></div></div>',
			hideOnMouseOut: false,
			copyClass: true,
			selectText: '.center',
			selectBtn: '.selectButton',
			selectDisabled: '.disabled',
			optStructure: '<div class="optionsDivVisible"><div class="select-top"></div><div class="select-center"><ul></ul><div class="select-bottom"></div></div>',
			optList: 'ul'
		}, _options);
		return this.each(function() {
			var select = $(this);
			if(!select.hasClass('outtaHere')) {
				if(select.is(':visible')) {
					var hideOnMouseOut = _options.hideOnMouseOut;
					var copyClass = _options.copyClass;
					var replaced = $(_options.selectStructure);
					var selectText = replaced.find(_options.selectText);
					var selectBtn = replaced.find(_options.selectBtn);
					var selectDisabled = replaced.find(_options.selectDisabled).hide();
					var optHolder = $(_options.optStructure);
					var optList = optHolder.find(_options.optList);
					if(copyClass) optHolder.addClass('drop-'+select.attr('class')); replaced.addClass(select.attr('class'));

					if(select.attr('disabled')) selectDisabled.show();
					select.find('option').each(function(){
						var selOpt = $(this);
						var _opt = $('<li><a href="#">' + selOpt.html() + '</a></li>');
						if(selOpt.attr('selected')) {
							selectText.html(selOpt.html());
							_opt.addClass('selected');
						}
						_opt.children('a').click(function() {
							optList.find('li').removeClass('selected');
							select.find('option').removeAttr('selected');
							$(this).parent().addClass('selected');
							selOpt.attr('selected', 'selected');
							selectText.html(selOpt.html());
							select.change();
							optHolder.hide();
							return false;
						});
						optList.append(_opt);
					});
					replaced.width(select.outerWidth());
					replaced.insertBefore(select);
					optHolder.css({
						width: select.outerWidth(),
						display: 'none',
						position: 'absolute'
					});
					$(document.body).append(optHolder);

					var optTimer;
					replaced.hover(function() {
						if(optTimer) clearTimeout(optTimer);
					}, function() {
						if(hideOnMouseOut) {
							optTimer = setTimeout(function() {
								optHolder.hide();
							}, 200);
						}
					});
					optHolder.hover(function(){
						if(optTimer) clearTimeout(optTimer);
					}, function() {
						if(hideOnMouseOut) {
							optTimer = setTimeout(function() {
								optHolder.hide();
							}, 200);
						}
					});
					selectBtn.click(function() {
						if(optHolder.is(':visible')) {
							optHolder.hide();
						}
						else{
							if(_activeDrop) _activeDrop.hide();
							optHolder.children('ul').css({height:'auto', overflow:'hidden'});
							optHolder.css({
								top: replaced.offset().top + replaced.outerHeight(),
								left: replaced.offset().left,
								display: 'block'
							});
							if(optHolder.children('ul').height() > 200) optHolder.children('ul').css({height:200, overflow:'auto'});
							_activeDrop = optHolder;
						}
						return false;
					});
					select.addClass('outtaHere');
				}
			}
		});
	}

	// event handler on DOM ready
	var _activeDrop;
	$(function(){
		$('body').click(hideOptionsClick)
		$(window).resize(hideOptions)
	});
	function hideOptions() {
		if(_activeDrop && _activeDrop.length) {
			_activeDrop.hide();
			_activeDrop = null;
		}
	}
	function hideOptionsClick(e) {
		if(_activeDrop && _activeDrop.length) {
			var f = false;
			$(e.target).parents().each(function(){
				if(this == _activeDrop) f=true;
			});
			if(!f) {
				_activeDrop.hide();
				_activeDrop = null;
			}
		}
	}
})(jQuery);
