/*
 * jQuery Allfilm Core
 *
 * For Allfilm OÜ - www.allfilm.ee
 *
 * @author: Alta Development Group <info@alta.ee>
 * @date: 01/11/2011
 */
 
 // Script: jQuery resize event
//
// *Version: 1.1, Last updated: 3/14/2010*
// 
// Project Home - http://benalman.com/projects/jquery-resize-plugin/
// GitHub       - http://github.com/cowboy/jquery-resize/
// Source       - http://github.com/cowboy/jquery-resize/raw/master/jquery.ba-resize.js
// (Minified)   - http://github.com/cowboy/jquery-resize/raw/master/jquery.ba-resize.min.js (1.0kb)
// 
// About: License
// 
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// This working example, complete with fully commented code, illustrates a few
// ways in which this plugin can be used.
// 
// resize event - http://benalman.com/code/projects/jquery-resize/examples/resize/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
// 
// jQuery Versions - 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome, Opera 9.6-10.1.
// Unit Tests      - http://benalman.com/code/projects/jquery-resize/unit/
// 
// About: Release History
// 
// 1.1 - (3/14/2010) Fixed a minor bug that was causing the event to trigger
//       immediately after bind in some circumstances. Also changed $.fn.data
//       to $.data to improve performance.
// 1.0 - (2/10/2010) Initial release

(function($,window,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  // A jQuery object containing all non-window elements to which the resize
  // event is bound.
  var elems = $([]),
    
    // Extend $.resize if it already exists, otherwise create it.
    jq_resize = $.resize = $.extend( $.resize, {} ),
    
    timeout_id,
    
    // Reused strings.
    str_setTimeout = 'setTimeout',
    str_resize = 'resize',
    str_data = str_resize + '-special-event',
    str_delay = 'delay',
    str_throttle = 'throttleWindow';
  
  // Property: jQuery.resize.delay
  // 
  // The numeric interval (in milliseconds) at which the resize event polling
  // loop executes. Defaults to 250.
  
  jq_resize[ str_delay ] = 250;
  
  // Property: jQuery.resize.throttleWindow
  // 
  // Throttle the native window object resize event to fire no more than once
  // every <jQuery.resize.delay> milliseconds. Defaults to true.
  // 
  // Because the window object has its own resize event, it doesn't need to be
  // provided by this plugin, and its execution can be left entirely up to the
  // browser. However, since certain browsers fire the resize event continuously
  // while others do not, enabling this will throttle the window resize event,
  // making event behavior consistent across all elements in all browsers.
  // 
  // While setting this property to false will disable window object resize
  // event throttling, please note that this property must be changed before any
  // window object resize event callbacks are bound.
  
  jq_resize[ str_throttle ] = true;
  
  // Event: resize event
  // 
  // Fired when an element's width or height changes. Because browsers only
  // provide this event for the window element, for other elements a polling
  // loop is initialized, running every <jQuery.resize.delay> milliseconds
  // to see if elements' dimensions have changed. You may bind with either
  // .resize( fn ) or .bind( "resize", fn ), and unbind with .unbind( "resize" ).
  // 
  // Usage:
  // 
  // > jQuery('selector').bind( 'resize', function(e) {
  // >   // element's width or height has changed!
  // >   ...
  // > });
  // 
  // Additional Notes:
  // 
  // * The polling loop is not created until at least one callback is actually
  //   bound to the 'resize' event, and this single polling loop is shared
  //   across all elements.
  // 
  // Double firing issue in jQuery 1.3.2:
  // 
  // While this plugin works in jQuery 1.3.2, if an element's event callbacks
  // are manually triggered via .trigger( 'resize' ) or .resize() those
  // callbacks may double-fire, due to limitations in the jQuery 1.3.2 special
  // events system. This is not an issue when using jQuery 1.4+.
  // 
  // > // While this works in jQuery 1.4+
  // > $(elem).css({ width: new_w, height: new_h }).resize();
  // > 
  // > // In jQuery 1.3.2, you need to do this:
  // > var elem = $(elem);
  // > elem.css({ width: new_w, height: new_h });
  // > elem.data( 'resize-special-event', { width: elem.width(), height: elem.height() } );
  // > elem.resize();
      
  $.event.special[ str_resize ] = {
    
    // Called only when the first 'resize' event callback is bound per element.
    setup: function() {
      // Since window has its own native 'resize' event, return false so that
      // jQuery will bind the event using DOM methods. Since only 'window'
      // objects have a .setTimeout method, this should be a sufficient test.
      // Unless, of course, we're throttling the 'resize' event for window.
      if ( !jq_resize[ str_throttle ] && this[ str_setTimeout ] ) { return false; }
      
      var elem = $(this);
      
      // Add this element to the list of internal elements to monitor.
      elems = elems.add( elem );
      
      // Initialize data store on the element.
      $.data( this, str_data, { w: elem.width(), h: elem.height() } );
      
      // If this is the first element added, start the polling loop.
      if ( elems.length === 1 ) {
        loopy();
      }
    },
    
    // Called only when the last 'resize' event callback is unbound per element.
    teardown: function() {
      // Since window has its own native 'resize' event, return false so that
      // jQuery will unbind the event using DOM methods. Since only 'window'
      // objects have a .setTimeout method, this should be a sufficient test.
      // Unless, of course, we're throttling the 'resize' event for window.
      if ( !jq_resize[ str_throttle ] && this[ str_setTimeout ] ) { return false; }
      
      var elem = $(this);
      
      // Remove this element from the list of internal elements to monitor.
      elems = elems.not( elem );
      
      // Remove any data stored on the element.
      elem.removeData( str_data );
      
      // If this is the last element removed, stop the polling loop.
      if ( !elems.length ) {
        clearTimeout( timeout_id );
      }
    },
    
    // Called every time a 'resize' event callback is bound per element (new in
    // jQuery 1.4).
    add: function( handleObj ) {
      // Since window has its own native 'resize' event, return false so that
      // jQuery doesn't modify the event object. Unless, of course, we're
      // throttling the 'resize' event for window.
      if ( !jq_resize[ str_throttle ] && this[ str_setTimeout ] ) { return false; }
      
      var old_handler;
      
      // The new_handler function is executed every time the event is triggered.
      // This is used to update the internal element data store with the width
      // and height when the event is triggered manually, to avoid double-firing
      // of the event callback. See the "Double firing issue in jQuery 1.3.2"
      // comments above for more information.
      
      function new_handler( e, w, h ) {
        var elem = $(this),
          data = $.data( this, str_data );
        
        // If called from the polling loop, w and h will be passed in as
        // arguments. If called manually, via .trigger( 'resize' ) or .resize(),
        // those values will need to be computed.
        data.w = w !== undefined ? w : elem.width();
        data.h = h !== undefined ? h : elem.height();
        
        old_handler.apply( this, arguments );
      };
      
      // This may seem a little complicated, but it normalizes the special event
      // .add method between jQuery 1.4/1.4.1 and 1.4.2+
      if ( $.isFunction( handleObj ) ) {
        // 1.4, 1.4.1
        old_handler = handleObj;
        return new_handler;
      } else {
        // 1.4.2+
        old_handler = handleObj.handler;
        handleObj.handler = new_handler;
      }
    }
    
  };
  
  function loopy() {
    
    // Start the polling loop, asynchronously.
    timeout_id = window[ str_setTimeout ](function(){
      
      // Iterate over all elements to which the 'resize' event is bound.
      elems.each(function(){
        var elem = $(this),
          width = elem.width(),
          height = elem.height(),
          data = $.data( this, str_data );
        
        // If element size has changed since the last time, update the element
        // data store and trigger the 'resize' event.
        if ( width !== data.w || height !== data.h ) {
          elem.trigger( str_resize, [ data.w = width, data.h = height ] );
        }
        
      });
      
      // Loop.
      loopy();
      
    }, jq_resize[ str_delay ] );
    
  };
  
})(jQuery,this);
 
(function ($) {
/*
 * jQuery AllFilmFlipMenu plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 01/11/2011
 */
    $.fn.AllFilmFlipMenu = function (options) {
        var options = $.extend({
            activeClass: 'current_page_item',
            animationSpeed: 250,
            slideMode: 'up',
            slideDownSpeed: '500',
            slideUpSpeed: '300'
		}, options),
            this_menu = $(this),
            menu_height = this_menu.height(),
            menu_position = this_menu.position(),
            animation_active = false;
        
        if (options['slideMode'] == 'up') {
            this_menu.children().prepend($('<span>'));
        } else {
            this_menu.children().append($('<span>').css('margin-top', -menu_height));
        }
        
        this_menu.children().each(function () {
            $(this).find('ul').css({
                'top': menu_position.top + menu_height,
                'min-width': $(this).width()
            });
        });
        
        this_menu.children().each(function () {
            var link_text = $(this).find('a').html();
            $(this).css({
                'cursor': 'pointer'
            }).find('span').show().html(link_text);
        }).hover(function () {
            if (options['slideMode'] == 'up') {
                new_margin = -menu_height;
            } else {
                new_margin = 0;
            }
            
            $(this).not('.' + options['activeClass']).find("span").stop().animate({
    		    marginTop: new_margin
            }, options['animationSpeed']);

            $(this).find('ul').delay(250).stop(true, true).slideDown(options['slideDownSpeed']);
			
    	}, function () {
            if (options['slideMode'] == 'up') {
                new_margin = 0;
            } else {
                new_margin = -menu_height;
            }
            
			$(this).not('.' + options['activeClass']).find("span").stop().animate({
				marginTop: new_margin
			}, options['animationSpeed']);
            
            $(this).find('ul').delay(300).slideUp(options['slideUpSpeed']);
    	});
        
        if (options['slideMode'] == 'up') {
            this_menu.find('li.' + options['activeClass'] + ' span').css('margin-top', -menu_height);
        } else {
            this_menu.find('li.' + options['activeClass'] + ' span').css('margin-top', 0);
        }
    };

/*
 * jQuery AllFilmSearch plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 15/11/2011
 */
    $.fn.AllFilmSearch = function (options) {
        var options = $.extend({
            menuWrapper: '#menu_bar',
            menu: '.menu ul',
            magnifierSelector: '#search_right'
        }, options),
            search_field = $('#search_wrapper input[type="text"]'),
            search_submit = $('#search_wrapper input[type="submit"]'),
            menu_av_width = $(options['menuWrapper']).outerWidth() - $(options['menu']).outerWidth();
        
        $(this).width(search_width = menu_av_width - 28 - 1); // 14x2=28 is the horizontal padding
        
        var search_submit_width = $(search_submit).outerWidth(),
            new_input_width = search_width - search_submit_width;
        
        $(search_field).width(new_input_width - (12 + 5 + 5 - 1)); // 12+26=38+5 are the corners and padding
        
        $(this).click(function () {
            $(search_field).focus();
        });
        $(search_field).focus(function () {
            $(options['magnifierSelector']).addClass('focus');
        });
        $(search_field).blur(function () {
            $(options['magnifierSelector']).removeClass('focus');
        });
    };

/*
 * kvSmoothTransition 1.1.0, jQuery plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 16/11/2011
 *
 * Dual licensed under the MIT and GPL
 * Originally made for http://stackoverflow.com/questions/6800950
 */
    var kvSmoothTransition_elms = {},
        kvSmoothTransition_runs = 0;
    $.fn.kvSmoothTransition = function (options) {
        var options = $.extend({
            showSpeed: 350,
            hideSpeed: 500,
            includeText: true
		}, options),
            elms = {};
            kvSmoothTransition_runs++;
        
        $('body, #content, .embedCU3ER').resize(function () {
        	kvSmoothTransitionRePosition();
        });
        
        return this.each(function (i, link) {
            
            var $this = $(this),
                this_position = $this.position();
                
            if ($.browser.msie) {
            	this_width = parseInt($this.width()) + 1;
            	
            } else {
            	this_width = $this.width();
            }

            $this.append(elms[i] = $('<div />').filter(function (index) {
                if (options['includeText']) {
                    $(this).html($this.html());
                }
                if ($this.attr('id')) {
                    $(this).attr('id', $this.attr('id'));
                }
                return true;
            }).addClass($this.attr('class') + ' hover').css({
                'display': 'block',
                'opacity': 0,
                'position': 'absolute',
                'top': this_position.top,
                'left': this_position.left,
                // 'width': parseInt($this.width()) + 1,
                'width': this_width,
                'height': $this.height(),
                'cursor': 'pointer',
                'overflow': 'hidden'
                
                // For testing: ,'border': '1px dotted blue'
            })).hover(function () {
                $(elms[i]).stop().animate({
                    'opacity': 1
                }, options['showSpeed']);
            }, function () {
                $(elms[i]).stop().animate({
                    'opacity': 0
                }, options['hideSpeed']);
            });
            kvSmoothTransition_elms[kvSmoothTransition_runs] = elms;
        });
    };
    kvSmoothTransitionRePosition = function () {
        $.each(kvSmoothTransition_elms, function (i, runs) {
            $.each(runs, function (i, value) {
                parent = $(value).parent();
                parent_position = parent.position();
                $(value).css({
                    'top': parent_position.top,
                    'left': parent_position.left,
                    'width': parent.width(),
                    'height': parent.height()
                });
            });
        });
    };

/*
 * jQuery kvListToTwoColumns plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 17/11/2011
 */
    $.fn.kvListToTwoColumns = function (options) {
        return this.each(function () {
            var $this = $(this),
                elements = $this.children('li'),
                elm_count = elements.length,
                breaking_point = (elm_count / 2),
                second_column = $('<ul />').addClass($(this).attr('class'));
            $.each(elements, function (i, element) {
                if (i >= breaking_point) {
                    second_column.append($(element));
                }
            });
            $(this).after(second_column).add(second_column).css({
                'float': 'left'
            });
        });
    };

/*
 * jQuery kvStringSplitWords plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 17/11/2011
 */
    $.fn.kvStringSplitWords = function (breaking_point, new_class) {
        return this.each(function () {
            var text = $.trim($(this).text()),
                text_splitted = text.split(' '),
                first_part = [],
                second_part = [];
            $.each(text_splitted, function (i, word) {
                if (i < breaking_point) {
                    first_part.push(word);
                } else {
                    second_part.push(word);
                }
            });
            $(this).text(' ' + second_part.join(' ')).prepend($('<span />').addClass(new_class).text(first_part.join(' ')));
        });
    };

/*
 * jQuery kvScrollToTop plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 18/11/2011
 */
    $.fn.kvScrollToTop = function (options) {
        var options = $.extend({
            min: 200,
            inDelay: 600,
            outDelay: 400,
            scrollSpeed: 1200
        }, options),
            $this = $(this);
        $this.hide().click(function () {
            $('html, body').animate({
                scrollTop: 0
            }, options.scrollSpeed);
        });
        $(window).scroll(function () {
            var sd = $(window).scrollTop();
            if (typeof document.body.style.maxHeight === "undefined") {
                $this.css({
                    'position': 'absolute',
                    'top': $(window).scrollTop() + $(window).height() - 50
                });
            }
            if (sd > options.min) {
                $this.fadeIn(options.inDelay);
            } else {
                $this.fadeOut(options.Outdelay);
            }
        });
    };

/*
 * jQuery kvImagePlayButton plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 18/11/2011
 */
	var kvImagePlayButton_elms = {},
        kvImagePlayButton_runs = 0;
    $.fn.kvImagePlayButton = function (options) {
        var options = $.extend({
            showSpeed: 350,
            hideSpeed: 500,
            overlayClass: '',
        }, options),
            elms = {};
			kvImagePlayButton_runs++;

        $('body, #content').resize(function () {
        	kvImagePlayButtonRePosition();
        });
        
        return this.each(function (i, value) {
            var $this = $(this)
                this_position = $this.position(),
                this_width = $this.width(),
                this_height = $this.height();
                
            $this.append(elms[i] = $('<span />').addClass(options.overlayClass).css({
                'display': 'block',
                'position': 'absolute',
                'opacity': 0,
                'top': this_position.top,
                'left': this_position.left,
                'width': this_width,
                'height': this_height,
                'cursor': 'pointer',
                'margin-left': $this.css('margin-left')
            })).hover(function () {
                $(elms[i]).stop().animate({
                    'opacity': 0.80
                }, options.showSpeed);
            }, function () {
                $(elms[i]).stop().animate({
                    'opacity': 0
                }, options.hideSpeed);
            });
            
            kvImagePlayButton_elms[kvImagePlayButton_runs] = elms;
        });
    };
    kvImagePlayButtonRePosition = function () {
        $.each(kvImagePlayButton_elms, function (i, runs) {
            $.each(runs, function (i, value) {
                parent = $(value).parent();
                parent_position = parent.position();
                $(value).css({
                    'top': parent_position.top,
                    'left': parent_position.left,
                    'width': parent.width(),
                    'height': parent.height()
                });
            });
        });
    };

/*
 * jQuery AllFilmAddClassAfter plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 19/11/2011
 */
    $.fn.AllFilmAddClassAfter = function (after, new_class) {
        if (!($.browser.msie && $.browser.version == 7.0)) {
            var elm_count = 0;
            return this.each(function (i, element) {
                elm_count++;
                if (elm_count == after) {
                    $(element).addClass(new_class);
                    elm_count = 1;
                }
            });
        }
    };

/*
 * jQuery AllFilmTwoColSeperatorHeightFix plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 19/11/2011
 */
    $.fn.AllFilmColSeperatorHeightFix = function () {
        return this.height(Math['max'].apply(this, $(this).map(function (i, element) {
            return $(element).outerHeight();
        }).get()));
    };

/*
 * jQuery AllFilmTwoColSeperatorHeightFix plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 19/11/2011
 */
    $.fn.AllFilmSubmitFix = function (next_button) {
        return this.each(function () {
            var $this = $(this).hide(),
                $new_button = $this.next().css('display', 'block').text($this.val()).click(function () {
                    $this.parent('form').submit();
                    
                }).kvSmoothTransition();
        });
    };

/*
 * jQuery AllFilmFocusFix plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 19/11/2011
 */
    $.fn.AllFilmFocusFix = function () {
        return this.each(function () {
            $(this).focus(function () {
                $(this).addClass('focus');
            });
            $(this).blur(function () {
                $(this).removeClass('focus');
            });
        });
    };

/*
 * jQuery kvDropSelect 1.2.0 plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 19/11/2011
 */
    $.fn.kvDropSelect = function (in_options) {

        // mkvds_objectgroup
        $.globalEval("var kvds_objectgroup = $()");

        // Loop trough all the element
        return this.each(function (i, select_object) {

            // Merge together input settings and defaults
            var options = $.extend({
                    newclass: '',
                    setwidth: false,
                    staticWidth: true,
                    openspeed: 'normal',
                    closespeed: 'fast',
                    trigger: 'click',
                    type: 'normal',
                    emptyvalfallback: true,
                    onclickappendarrow: true,
                    changemainvalue: true,
                    maxheight: false,
                    onblurhide: true,
                    group: '',
                    focusClass: 'focus'
                }, in_options),
                select_title = $(select_object).children('option').first().text(),
                select_name = $(select_object).attr('name'),
                select_classes = $(select_object).attr('class');
                
            // Set global variable zindex, so they woulnt overlap each other
            $.globalEval("var kvds_zindex = 100");

            // Create subgroup to object-list, when one does not already exist
            if (!kvds_objectgroup[options.group]) {
                kvds_objectgroup[options.group] = $();
            }

            // This will replace the original element and..
            $(this).replaceWith(
                // ..create the main wrapper
                new_wrapper = $('<div />').addClass(options.newclass + ' ' + select_classes),
                // ..select title, otherwise the arrow woulnt look good
                new_select = $('<div />').html(select_title).addClass('title'),
                // ..and finally the arrow
                new_select_arrow = $('<div />').html('&nbsp;').addClass('arrow')
            );
            
            // Because arrow and title collation needs to be in the right order, then we cannot append them above just yet
            if ($(new_wrapper).css('float') == 'left') {
                $(new_select).appendTo($(new_wrapper));
                $(new_select_arrow).appendTo($(new_wrapper));
            } else {
                $(new_select).prependTo($(new_wrapper));
                $(new_select_arrow).prependTo($(new_wrapper));
            }
            
            // This sets the width, either from settings or automatically from the object
            if (options.setwidth) {
                $(new_wrapper).width(options.setwidth);
            } else if (options.staticWidth) {
                $(new_wrapper).width($(new_wrapper).width());
            }
            
            if (options.type == 'normal') {
                $(new_wrapper).after(hidden_input = $('<input type="hidden" name="' + select_name + '" value="">'));
            }
            
            // This is the dropdown itself. Note that it will need margin-top..or it would be placed over the $(new_wrapper))
            var new_dropdown = $('<ul />').hide().addClass('options_wrapper').css({
                'top': $(new_wrapper).position().top + $(new_wrapper).outerHeight() + parseInt($(new_wrapper).css('margin-top')),
                'width': $(new_wrapper).width()
            }).prependTo($(new_wrapper));

            // For grouping effect we will add this to a object-array.
            kvds_objectgroup[options.group].add($(new_dropdown));

            // Opening function with the group-close
            var func_dropdown_open = function () {
                    kvds_objectgroup[options.group].slideUp(options.closespeed);
                    $(new_wrapper).addClass(options.focusClass);
                    $(new_dropdown).css('z-index', ++kvds_zindex).slideDown(options.openspeed);
                },
                // Closing function
                func_dropdown_close = function () {
                    $(new_wrapper).removeClass(options.focusClass);
                    $(new_dropdown).slideUp(options.closespeed);
                };

            // Loop trough all the options and create the dropdown list
            $('option', select_object).each(function (i, option) {
                
                // Generate new list item and append it to dropdown
                $(new_dropdown).append(list_item = $('<li />').text($(option).text()));
                
                // If we are dealing with onclick mode, then there is no need for first item
                if (i == 0 && options.type == 'onclick') {
                    $(list_item).hide();
                }
                
                $(list_item).click(function () {
                    
                    if (options.type == 'normal') {
                        
                        if ($(option).val()) {
                            
                            $(hidden_input).val($(option).val());
                            
                        } else if ($(option).text() == select_title) {
                            
                            $(hidden_input).val('');
                            
                        } else if (options.emptyvalfallback == true) {
                            
                            $(hidden_input).val($(option).val());
                            
                        } else {
                            
                            $(hidden_input).val('');
                            
                        }
                        
                    } else if (options.type == 'onclick') {
                        
                        eval($(option).attr('onclick'));
                        
                    }
                    
                    if (options.changemainvalue) {
                        $(new_select).text($(option).text());
                    }
                    
                    if (!options.staticWidth) {
                        $(new_dropdown).width($(new_wrapper).width())
                    }
                    
                    func_dropdown_close();
                    
                });
                
            });
            
            
            if (options.trigger == 'click') {
                
                $(new_wrapper).click(function () {
                    if ($(new_dropdown).is(':visible')) {
                        func_dropdown_close();
                    } else {
                        func_dropdown_open();
                    }
                });
                
            } else if (options.trigger == 'hover') {
                
                $(new_wrapper).mouseover(function () {
                    if ($(new_dropdown).is(':hidden')) {
                        func_dropdown_open();
                    }
                });
                
                $(new_wrapper).click(function () {
                    if ($(new_dropdown).is(':hidden')) {
                        func_dropdown_open();
                    } else {
                        func_dropdown_close();
                    }
                });
                
            }
            
            // This hides all dropdowns, when clicked outside
            if (options.onblurhide) {
                $('body').click(function() {
                    func_dropdown_close();
                });
                $(new_wrapper).click(function(e) {
                    e.stopPropagation();
                });
            }
            
        });
    };

/*
 * jQuery AllFilmTabScrollToTable plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 22/11/2011
 */
    $.fn.AllFilmTabScrollToTable = function (in_options) {
         var options = $.extend({
                scrollSpeed: 1200,
                extraSpace: 15
            }, in_options);
        return this.each(function () {
            $(this).click(function () {
                var button_text = $(this).contents().filter(function(){ return this.nodeType == 3; }).text(),
                    anchor = $('.list tr th:contains("' + button_text + '")');
                $('html, body').stop().animate({
                    scrollTop: $(anchor).offset().top - options.extraSpace
                }, options.scrollSpeed);
            });
        });
    };

/*
 * jQuery PlaceHolderSupport plugin
 */
    $.fn.PlaceHolderSupport = function (options) {
        return this.each(function () {
            $(this).focus(function() {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                    input.removeClass('placeholder');
                }
            }).blur(function() {
                var input = $(this);
                if (input.val() == '' || input.val() == input.attr('placeholder')) {
                    input.addClass('placeholder');
                    input.val(input.attr('placeholder'));
                }
            }).blur().parents('form').submit(function() {
                $(this).find('[placeholder]').each(function() {
                    var input = $(this);
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                })
            });
        });
    };

/*
 * jQuery centerit plugin
 */
    $.fn.centerit = function () {
    	return this.each(function () {
    		$(this).css("position", "absolute");
    		$(this).css("top", (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop() + "px");
    		$(this).css("left", (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft() + "px");
    	});
    };

/*
 * jQuery AllfilmClientLogin plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 11/12/2011
 */
    $.fn.AllfilmClientLogin = function (wrapper, target_box) {
    	var $this = $(this),
    		$wrapper = $(wrapper),
			$password = $('#cl_password'),
			$pw_label = $('#cl_pw_label'),
			$target = $(target_box).centerit();
    	
    	$this.click(function () {
    		$wrapper.fadeIn('normal', function () {
    			$password.focus();
    		})
    		return false;
    	});
		
		submit_func = function () {
			$.post(ajaxurl, {
				action: 'CLIENT_LOGIN',
				cl_password: $password.val(),
				_ajax_nonce: cl_nonce
			}, function(response) {
				if (response == 'OK') {
					window.location.href = cl_location;
					$wrapper.fadeOut();
				} else if (response == 'NG') {
					$pw_label.before($('<div />').text(cl_wp_text).addClass('wrong_password_text'));
					$password.addClass('wrong_password');
				}
			});
		};
		
		func_close = function () {
			$wrapper.fadeOut();
		};
		
		$password.keyup(function (e) {
			if ((e.keyCode == 13)) {
				submit_func();
			}
		});
		
		$target.find('.cancel').click(function () {
			func_close();
		});
		
		$(document).keydown(function(e) {
			if (e.keyCode == 27) {
				func_close();
			}
		});
		
		$('#cl_login').click(function () {
			submit_func();
		});

		$wrapper.click(function () {
			func_close();
		});
		$target.click(function (e) {
			e.stopPropagation();
		});
    };

/*
 * jQuery AllfilmVideoPopper plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 20/12/2011
 */
	getUrlVars = function (url) {
		var vars = [], hash;
		var hashes = url.href.slice(url.href.indexOf('?') + 1).split('&');
		for (var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	};
    $.fn.AllfilmVideoPopper = function () {
    	return this.each(function (i, link) {
    		var permalink = $(this);
    		
    		$(permalink).click(function () {
    			
	   			if (permalink.attr('id')) {
	    			vid = permalink.attr('id').replace('vid-', '');
	    		} else {
	    			vid = getUrlVars(link)['vid'];
	    		}
    			
    			$('body').append(
					$body_overlay = $('<div class="body_overlay" />').append(
						$wrapper = $('<div class="video_popper_wrapper">').append(
							$closing_button = $('<div class="popper_close" />'),
							$player = $('<iframe src="' + vp_iframe_dir + '?vid=' + vid + '" class="video_popper"></iframe>')
						)
					)
				);
				
				$body_overlay.fadeIn();
				
				func_close = function () {
					$body_overlay.fadeOut('fast', function () {
						$(this).remove();
					});
				};
				
				$closing_button.click(function () {
					func_close();
				});
				$body_overlay.click(function () {
					func_close();
				});
				$wrapper.click(function (e) {
					e.stopPropagation();
				});
				
				$(document).keydown(function(e) {
					if (e.keyCode == 27) {
						func_close();
					}
				});

    			return false;
    		});
    		
    	});
    };

/*
 * jQuery AllfilmPicturePopper plugin
 *
 * @author: Kalle H. Väravas <kalle.varavas@alta.ee>
 * @date: 22/12/2011
 */
    $.fn.AllfilmPicturePopper = function () {
    	return this.each(function (i, link) {
    		var image = $(this);
    		
    		$(image).click(function () {
    			
    			var img = new Image();
    			
				$('body').append(
					$body_overlay = $('<div class="body_overlay" />').append(
						$wrapper = $('<div id="picture_popper_wrapper">').append(
							$closing_button = $('<div class="popper_close" />'),
							$viewer = $('<img src="' + $(image).attr('href') + '" />')
						)
					)
				);
    			
				$(img).load(function () {
					$wrapper.css('width', img.width);
					$body_overlay.fadeIn();
					console.log($closing_button.position());
				});
				
				img.src = $(image).attr('href');

				func_close = function () {
					$body_overlay.fadeOut('fast', function () {
						// $player.remove();
					})
				};
				
				$closing_button.click(function () {
					func_close();
				});
				$body_overlay.click(function () {
					func_close();
				});
				$viewer.click(function (e) {
					e.stopPropagation();
				});
				
				$(document).keydown(function(e) {
					if (e.keyCode == 27) {
						func_close();
					}
				});
    			
    			return false;
    		});
    		
    	});
    };
}) (jQuery);
