/**
 * @author		Firstname Lastname
 * @copyright	http://www.divio.ch
 */
var log;
// check if console.log is available and register log(msg) or $(el).log(msg)
if(window['console'] === undefined) {
	window.console = { log: function(){}, debug: function(){} }; } else {
	log = (window.ActiveXObject) ? function (msg) { console.debug(msg); } : console.log;
};

// allow jQuery to chain .log
if('jQuery' in window && log) jQuery.fn.log = function(msg) { log("%s: %o", msg, this); return this; };

// set namespace
var BASE = {};

/**
 * CUSTOM MODULES
 * ##################################################|
 */
(function ($) {
/* private scope - do it the moo way */

	BASE = {
		init: function() {
			// initiate ie6 fixes
			if(!window.XMLHttpRequest) this.ie6();
			// initiate gecko fixes
			if($.browser.mozilla) this.gecko();
			// do horizontal resizing
			this.resize();
			
			// general confirm prompt
			if($('.confirm').length) {
				$('.confirm').bind('click', function (e) {
					var $test = confirm('Sind Sie sicher, dass Sie die ausgewählten Daten unwiederruflich löschen möchten?');
					if(!$test) return false;
				});
			}
		},
		ie6: function () {
			// pseudo fixes
			$.fn.fix_pseudos = function(options) {
				this.filter(":first-child").addClass("first-child");
				this.filter(":last-child").addClass("last-child");
			};
		},
		gecko: function () {
			//console.log($(document.body).parent());
			$(document.body).parent().css('height', '100.01%');
		},
		resize: function () {
			var cols = $('.col_left, .col_right');
			var main = $('#main');
			// overwrite initial width
			main.css('width', '100%');
			cols.css('width', ($(document.body).width()-640)/2);
			// inizial resize background
			resizeBackground();
			// attach resize event
			$(window).bind('resize', function () {
				$(document.body).css('overflow', 'overflow-x');
				
				// resize canvas to full browser width
				if($(document.body).width() >= 960) {
					main.css('width', '100%');
					cols.css('width', ($(document.body).width()-640)/2);
				// if canvas reaches 960 px or below, deactivate resizing
				} else {
					main.css('width', 960);
					cols.css('width', 160);
				}
				// resize background
				resizeBackground();
			})
			// background function
			function resizeBackground() {
				var bg = $('#background img');
					bg.css('width', $(document.body).width());
			}
		}
	};
	BASE.init();
	
	/* login collapser */
	BASE.login = {
		init: function () {
		var container = $('.frm_login');
			container.hide();
		var trigger = $('.mainnav .login');
			trigger.bind('click', function (e) {
				e.preventDefault();
				container.slideToggle();
				//$(this).html('&nbsp;');
				$(this).addClass('active');
				
				// adjust position
				container.css({
					'position': 'relative',
					'top': '-120px'
				});
			});
			
			// handle login
			var form = $('.frm_login');
			var button = $('#submitBtn');
				button.bind('click', function (e) {
					e.preventDefault();
					form.submit();
				});
		}
	};
	BASE.login.init();
	
	/* sidebar subnav hide text */
	BASE.sidebar = {
		init: function () {
			var items = $('.sidebar .subnav li a');
			
			// check if there are images
			items.each(function (index, item) {
				if($(item).find('img').length) {
					$(item).find('span').hide();
					
					// check for initial actives
					$(item).each(function (index, item) {
						if($(item).parent().hasClass('active')) {
							$(item).parent().find('span').show();
						}
					});
					
					$(item).bind('mouseenter mouseleave', function (e) {
						if($(item).parent().hasClass('active')) {
							$(e.currentTarget).find('span').show();
							return false;
						}
						//console.log(e);
						if(e.type == 'mouseenter') {
							$(e.currentTarget).find('span').show();
						} else {
							$(e.currentTarget).find('span').hide();
						}
					});
				}
			});
			
			
		}
	};
	BASE.sidebar.init();
	
	/* new video player */
	BASE.video = {
		init: function () {
			var player = swfobject.getObjectById('flash');
			var container = $('#player_canvas');
			var state = false;
			
			var items = $('.subvideo a:first-child');
				items.each(function (index, item) {
					var item = $(item);
						item.bind('click', function (e) {
							e.preventDefault();
							
							var attr = item.attr('rel').split('::');
							
							// set container size
							container.css({
								'width': attr[1] + 'px',
								'height': attr[2] + 'px'
							});

							// change video settings
							player.sendEvent('LOAD', {
								'file': attr[0],
								'image': attr[3]
							});
							
							// autoplay
							player.sendEvent('PLAY', true);
							
							//onsole.log(state);
						});
				});
		}
	};
	BASE.video.init();
	
	/* playlist behaviour */
	BASE.playlist = {
		init: function () {
			var items = $('.subvideo').find('li');
				$(items[0]).addClass('active');
				items.bind('click', function (e) {
					items.removeClass('active');
					$(this).addClass('active');
				});
		}
	};
	if($('.subvideo').length) BASE.playlist.init();
	
	/* admin functions */
	BASE.admin = {
		init: function () {
			this.collapser();
		},
		collapser: function () {
			var table = $('.tbl_default');
				table.find('.trigger-item').hide();
			
			var items = $('.trigger');
				items.each(function (index, item) {
					item = $(item);
					item.bind('click', function (e) {
						e.preventDefault();
						e.stopPropagation();
						var parent = $(this).parentsUntil('.mainrow')
							.parent()
							.attr('class')
							.replace('mainrow mainparent_', 'parent_');
						
						(table.find('.'+parent).css('display') == 'none') ? expand(parent, $(this)) : collapse(parent, $(this));
					});
				});
			
			// add tr event
			$('.tbl_default .mainrow').bind('click', function (e) {
				$(this).find('.mainparent_icon').trigger('click');
			});
			
			function expand(parent, trigger) {
				table.find('.'+parent).show();
				// change icon
				if(trigger != 'undefined') {
					trigger.find('img').attr('src', '/media/img/icons/icon_collapse.png');
				}
			}
			
			function collapse (parent, trigger) {
				table.find('.'+parent).hide();
				// change icon
				if(trigger != 'undefined') {
					trigger.find('img').attr('src', '/media/img/icons/icon_expand.png');
				}
			}
			
			// show all
			$('.show_all').bind('click', function (e) {
				e.preventDefault();
				table.find('.trigger-item').show();
				table.find('.mainparent_icon').attr('src', '/media/img/icons/icon_collapse.png');
			});
		}
	};
	BASE.admin.init();

/**
 * HELPER MODULES
 * ##################################################|
 */
	/**
	 * Flash Video Player
	 * @version: 0.1.0
	 */
	$.fn.videoPlayer = function (options) {
		$that = this;
		var options = $.extend({
			videoUrl: 'video/',
			imageUrl: '/media/swf/video/',
			autostart: false,
			height: 360
		}, options);
		
		// save player object
		var player = swfobject.getObjectById('flash');
		var state = options.autostart;
		var equal = false;
		
		// keep chaining
		return this.each(function (i, el) {
			el = $(el);
			el.find('li a')
				.bind('mouseenter', update)
				.bind('click', toggle);
			// attach seperate events
		});
		
		// update display settings
		function update(obj, autostart) {
			// stop events while playing
			if(status) return false;
			// update active status
			var parent = $(obj.currentTarget).closest('ul').find('li');
				parent.removeClass('active');
			var child = $(obj.currentTarget).parent();
				child.addClass('active');
			// change player options
			updateVideo($(obj.currentTarget).attr('rel'));
			// update height
			var height = $(obj.currentTarget).attr('class').split(':')[1];
				if(height) $('#player_canvas').css('height', height);
			// start player
			if(autostart) play(obj);
		}
		
		// update video player
		function updateVideo(rel) {
			player.sendEvent('LOAD', {
				'file': options.videoUrl + rel + '.mp4',
				'image': options.imageUrl + rel + '.jpg'
			});
			//console.log('update');
		}
		
		// toggle play/pause
		function toggle(obj) {
			// get player status
			
			// check if its the same item
			equal = $(obj.currentTarget).parent().hasClass('active');
			// play or pause
			(status) ? pause(obj) : play(obj);
		}
		
		// paly video
		function play(obj) {
			status = true;
			player.sendEvent('PLAY', true);
		}
		
		// pause video
		function pause(obj) {
			status = false;
			player.sendEvent('PLAY', false);
			//console.log(equal);
			if(!equal) update(obj, true);
		}
	};
	//$('.subnav').videoPlayer();

	/**
	 * Target modifier
	 * @version: 0.3.0
	 * @param: property (target:blank)
	 * @example: <a href="#" rel="target:blank">Lorem Ipsum</a>
	 */
	$.fn.defineTarget = function (options) {
		var options = $.extend({ property: 'rel' }, options);
		return this.each(function () {
			$(this).attr('target', '_' + $(this).attr(options.property).split(':')[1]);
		});
	};
	$('a[rel*="target:"]').defineTarget();
	$('a[class*="target:"]').defineTarget({ property: 'class' });

	/**
	 * E-Mail encrypter
	 * @version: 0.3.0
	 * @param: autoConvert (converts innerhtml to match the email address)
	 * @example: <a href="#info" rel="divio.ch" class="mailcrypte">E-Mail</a>
	 */
	$.fn.mailcrypter = function (options) {
		var options = $.extend({
			autoConvert: true
		}, options);

		return this.each(function () {
			var mailto = 'mailto:' + $(this).attr('href').replace('#', '') + '@' + $(this).attr('rel');
			$(this).attr('href', mailto);
			if(options.autoConvert) $(this).html(mailto.replace('mailto:', ''));
		});
	};
	if($('a.mailcrypte').length) $('a.mailcrypte').mailcrypter({ autoConvert: false });

	/**
	 * Pop-Up Generator
	 * @version: 0.2.0
	 * @param: width (initial width)
	 * @param: height (initial height)
	 * @example: <a href="http://www.google.ch" class="popup">Open Pop-Up</a>
	 */
	$.fn.autopopup = function (options) {
		var options = $.extend({ width: 750, height: 500}, options);
		// set vars
		var url = this.attr('href');
		var size = { 'x': options.width, 'y': options.height };

		// attach event
		return this.bind('click', function (e) {
			e.preventDefault();
			window.open(url, '_blank', 'width=' + size.x + ',height=' + size.y + ',status=yes,scrollbars=yes,resizable=yes');
		});
	};
	$('.popup').autopopup();

	/**
	 * Auto input fill-in
	 * @version: 0.6.0
	 * @param: label (if true than labeltext on parent else rel attribut on this)
	 * @param: strip (replacement text)
	 * @param: add (add additional information)
	 */
	$.fn.fieldLabel = function (options) {
		var options = $.extend({
			label: true,
			strip: '',
			add: ''
		}, options);

		// show functionality
		function show(el, e, label) {
			if(el.attr('value') != '') return false;
			el.attr('value', label);
		};

		// hide functionality
		function hide(el, e, label) {
			if(e.type == 'blur' && el.attr('value') == label) return false;
			el.attr('value', '');
		};

		return this.each(function () {
			// store label element and use replacement
			var label = (options.label == true) ? $(this).parent().find('label').text() : label = $(this).attr('rel');
			label = label.replace(options.strip, '');
			label += options.add;

			// initialize
			if($(this).attr('value') == '') $(this).attr('value', label);

			// attach event
			$(this).bind('click', function (e) {
				if($(this).attr('value') == label) hide($(this), e, label)
			})
			$(this).bind('blur', function (e) {
				($(this).attr('value') == label) ? hide($(this), e, label) : show($(this), e, label);
			})
		})
		
	};
	//$('.fieldLabel').fieldLabel({ strip: ': ', add: '...' });

})(jQuery);
//jQuery(document).ready(function ($) { });
