(function($){
	// I solemnly swear I'm up to no good...
	$(document).ready(function(){
		if ( $('#sidebar .widget').length != 0 ) {
			$('#sidebar .widget').each(function(){
				$(this).find('h2.widgettitle').remove().prependTo($(this));
			})
		};
		if ( $('.page-template-cnt').length != 0 ) {
			var height = 0;
			var tmp_h = 0;
			var hdng_cor = 0;
			var margin = 0;
			if ( $('.page-template-cnt').find('.post-content').length > $('.page-template-cnt').find('.col').length ) {
				$('.page-template-cnt').find('.col').each(function(){
					tmp_h = 0;
					if ( $(this).find('.post-content').length > 1 ) {
						$(this).find('.post').each(function(){
							tmp_h += $(this).outerHeight(true);
						});
					};
					margin = $(this).find('.post:eq(0)').outerHeight(true) - $(this).find('.post:eq(0)').innerHeight();
					hdng_cor = $(this).find('.post:eq(0) .post-header').outerHeight(true) + margin;
					height = Math.max(height, tmp_h - hdng_cor);
				})
			} else {
				$('.page-template-cnt').find('.col').each(function(){
					if ( $(this).find('.post-content').length == 1 ) {
						height = Math.max(height, $(this).find('.post-content').height());
					};
				})
			};
			if ( height != 0 ) {
				$('.page-template-cnt').find('.col').each(function(){
					if ( $(this).find('.post-content').length == 1 ) {
						$(this).find('.post-content').css('min-height', height + 'px');
					};
				})
			};
		};

		if ( $('#gallery-page-galleries').length != 0 ) {
			load_gallery_cnt($('#gallery-page-galleries').find('.col:eq(0) .gallery-data'));
		};

		// Blinking Fields
		$('.blink').
		    focus(function() {
		        if(this.title==this.value) {
		            this.value = '';
		        }
		    }).
		    blur(function(){
		        if(this.value=='') {
		            this.value = this.title;
		        }
		});
		
		// Student Login Popup
		$('.student-login-link').click(function(){
			if ($('.background-control').is(':visible')) {
				$('.background-control').fadeOut();
			}
			$('.student-login').fadeIn();
			
			return false;
		});
		
		// Background Control
		$('.bg-control-link').click(function(){
			if ($('.student-login').is(':visible')) {
				$('.student-login').fadeOut();
			}
			$('.background-control').fadeIn();
			return false;
		});

		$('.background-control ul li a').click(function(){
			var li = $(this).parents('li'),
				bg = $(li).data('bg'),
				video = $(li).data('video'),
				is_yt = $(li).data('is_yt'),
				top = $(li).data('bg_top'),
				id = $(li).data('id'),
				bg_id = $(li).index();
			if ( video != false && video == '' ) {
				return;
			};
			$('.background-control ul li').removeClass('active');
			$(li).addClass('active');
			$('.bg-control-link span').text(bg_id + 1);
			if ( video != false && typeof(video) != 'undefined' ) {
				$('body').addClass('video-bg').css({'background': 'none #000'});
				var video_started = ( window.__bg_video_started == true )? true : false;
				window.__stop_vimeo_vid();
				window.__stop_bg_video();
				if ( is_yt == true ) {
					window.__bg_video_started = video_started;
					window.__play_bg_video(video);
				} else {
					window.__play_vimeo_vid(video);
				};
			} else {
				$('body').removeClass('video-bg').css({'background': '#000 url(' + bg + ') no-repeat fixed center ' + top});
				window.__stop_bg_video();
				window.__stop_vimeo_vid();
			};
			$(this).parents('.background-control').hide();
			$.cookie('kukkiwon_bg', id, {
				path: '/'
			});
			return false;
		})
		
		// Toggle Fullscreen
		$('.toggle-fullscreen').click(function(){
			if (!$(this).hasClass('toggle-fullscreen-closed')) {
				$(this).addClass('toggle-fullscreen-closed');
				var active = $('.background-control ul li.active');
				var img = $(active).data('bg');
				var video = $(active).data('video');
				if ( video != false && video != '' && typeof(video) != 'undefined' ) {
					var is_yt = $(active).data('is_yt');
					if ( is_yt ) {
						window.__pause_yt_vid();
						$.colorbox({
							href: 'http://www.youtube.com/embed/' + video + '?wmode=transparent',
							iframe: true,
							width: '95%',
							height: '95%',
							onClosed: function(){
								$('.toggle-fullscreen').removeClass('toggle-fullscreen-closed');
								window.__unpause_yt_vid();
							}
						});
					} else {
						window.__pause_vimeo_vid();
						$.colorbox({
							href: 'http://player.vimeo.com/video/' + video,
							iframe: true,
							width: '95%',
							height: '95%',
							onClosed: function(){
								$('.toggle-fullscreen').removeClass('toggle-fullscreen-closed');
								window.__unpause_vimeo_vid();
							}
						});
					};
				} else {
					$.colorbox({
						href: img,
						onClosed: function(){
							$('.toggle-fullscreen').removeClass('toggle-fullscreen-closed');
						}
					});
				};
			} else {
				$(this).removeClass('toggle-fullscreen-closed');
			};
			
			return false;
		});
		
		$('#news-events-content .col-mid .list-entries li:last').addClass('last');

		// Navigation Dropdown
		$('#navigation ul li').hover(function(){
			$(this).find('a:eq(0)').toggleClass('hover');	
			$(this).find('ul:eq(0)').toggle();
		});
		
		// Main Slider init
		$('#main-slider ul').jcarousel({
			auto: 5,
			scroll: 1,
			visible: 1,
			wrap: "both"
		});
		

		// Gallery pages content loading
		$('.load-gallery').click(function(){
			load_gallery_cnt($(this).parents('.col').find('.gallery-data'));
			return false;
		})

	});

	function load_gallery_cnt (el) {
		if ( $(el).length == 0 ) {
			return false;
		};

		$('.post-header').removeClass('red-bg active');
		$(el).parent().find('.post-header').addClass('red-bg active');

		if ( $(el).hasClass('video') || $(el).hasClass('image') ) {
			$('#main-image').html($(el).html()).show();
			$('#main-slider').hide();
		} else if ( $(el).hasClass('slider') ) {
			if ( $.trim($('#main-slider').html()) != '' ) {
				var size = $(el).find('li').length;
				gallery_carousel.remove();
				$('#main-slider').html($(el).html()).show();
				setup_gallery_carousel();
			} else {
				$('#main-slider').html($(el).html()).show();
				setup_gallery_carousel();
			};

			$('#main-image').hide();
		};
	}

	function gallery_sliders_cb (carousel, state) {
		gallery_carousel = carousel;
	}

	function setup_gallery_carousel () {
		$('#main-slider ul').jcarousel({
			auto: 5,
			scroll: 1,
			visible: 1,
			wrap: "both",
			initCallback: gallery_sliders_cb
		});
	}

	// Close Popups on body click
	$(document).click(function(e) {
		if ($(e.target).parents('.student-login, .background-control').length == 0) {
			$('.student-login, .background-control').fadeOut();
		}
	});

	window.__play_vimeo_vid = function (video_id) {
		if ( $('iframe#vimeoBgPlayer').length != 0 ) {
			$('iframe#vimeoBgPlayer').attr('src', 'http://player.vimeo.com/video/' + video_id + '?api=1&amp;player_id=player_1')
		} else {
			$('#chromelessInner #chromelessScreen').before('<iframe id="vimeoBgPlayer" src="http://player.vimeo.com/video/' + video_id + '?api=1&amp;player_id=vimeoBgPlayer" width="100%" height="100%" frameborder="0"></iframe>')
		};
		$f(document.getElementById('vimeoBgPlayer')).addEvent('ready', window.__vimeo_player_ready);
	}

	window.__stop_vimeo_vid = function () {
		if ( $('iframe#vimeoBgPlayer').length != 0 ) {
			$('iframe#vimeoBgPlayer').remove();
		}
	}

	window._log = function (msg) {
		$('#debug-block').append('<p>' + msg + '</p>');
	}
})(jQuery)

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


(function(){
    /**
     * Called once a vimeo player is loaded and ready to receive
     * commands. You can add events and make api calls only after this
     * function has been called.
     */
    window.__vimeo_player_ready = function (player_id) {

    	froogaloop = $f(player_id);
        
        froogaloop.api('play');
        froogaloop.api('setVolume', 0);
        froogaloop.api('setLoop', 1);

        window.__pause_vimeo_vid = function () {
        	froogaloop.api('pause');
        }
        window.__unpause_vimeo_vid = function () {
        	froogaloop.api('play');
        }
    }
})();
