//
// jResizer 2.0
// unobtrusive resizing of font sizes and line heights
// vm @ Sonce.net
//
// Change only config options here
//

var ContentBoxId = 'content'; // ID elementa z vsebino
var FontResizeButton = 't-fontsize'; // ID gumba za povecavo teksta
var LineHeightButton = 't-lineheight'; // ID gumba za povecavo razmaka med vrsticami
var PrintButton = 't-print'; // ID gumba za tiskanje
var FontCssSizeUnits = 'px'; // Enota za velikost pisave (px ali em)
var LineCssSizeUnits = 'em'; // Enota za razmak vrstic (px ali em)
var UniqueCookieName = 'perovo'; // Unikatno ime za piskotke tega site-a
var AllFontSizes = Array(13, 15, 17); // Seznam velikosti pisav - prva se nastavi sama
var AllLineHeights = Array(1.38, 1.69, 2.0); // Seznam razmakov vrstic - prva se nastavi sama

//
// jQuery Cookie implementation
//

jQuery.cookie = function(name, value, options) {
 if (typeof value != 'undefined') { // name and value given, set cookie
 options = options || {};
 if (value === null) {
 value = '';
 options.expires = -1;
 }
 var expires = '';
 if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
 var date;
 if (typeof options.expires == 'number') {
 date = new Date();
 date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
 } else {
 date = options.expires;
 }
 expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
 }
 // CAUTION: Needed to parenthesize options.path and options.domain
 // in the following expressions, otherwise they evaluate to undefined
 // in the packed version for some reason...
 var path = options.path ? '; path=' + (options.path) : '';
 var domain = options.domain ? '; domain=' + (options.domain) : '';
 var secure = options.secure ? '; secure' : '';
 document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
 } else { // only name given, get cookie
 var cookieValue = null;
 if (document.cookie && document.cookie != '') {
 var cookies = document.cookie.split(';');
 for (var i = 0; i < cookies.length; i++) {
 var cookie = jQuery.trim(cookies[i]);
 // Does this cookie string begin with the name we want?
 if (cookie.substring(0, name.length + 1) == (name + '=')) {
 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
 break;
 }
 }
 }
 return cookieValue;
 }
};

//
// Array Prototype implementation
//

Array.prototype.indexOf = function(a) {
 for (var i in this) {
 if (this[i]==a) {
 return i;
 }
 } 
 return false;
}

//
// Text resizing and line height functions
//

$(document).ready(function(){

 // Font resize
 if($.cookie('fontsize_' + UniqueCookieName) == null) {
 $.cookie('fontsize_' + UniqueCookieName, AllFontSizes[0], { expires: 7, path: '/', domain: '', secure: false });
 $('#' + ContentBoxId).css({
 'font-size': AllFontSizes[0] + FontCssSizeUnits
 });
 } else {
 $('#' + ContentBoxId).css({
 'font-size': $.cookie('fontsize_' + UniqueCookieName) + FontCssSizeUnits
 });
 }
 
 $('#' + FontResizeButton).click(function(){
 var CurrentFontSize = parseFloat(AllFontSizes.indexOf($.cookie('fontsize_' + UniqueCookieName))) + parseFloat(1);
 if(CurrentFontSize == AllFontSizes.length) {
 NewFontSize = AllFontSizes[0];
 } else {
 NewFontSize = AllFontSizes[CurrentFontSize];
 }
 $.cookie('fontsize_' + UniqueCookieName, NewFontSize, { expires: 7, path: '/', domain: '', secure: false });
 $('#' + ContentBoxId).css({
 'font-size': NewFontSize + FontCssSizeUnits
 });
 return false;
 });
 
 // Change line height
 if($.cookie('lineheight_' + UniqueCookieName) == null) {
 $.cookie('lineheight_' + UniqueCookieName, AllLineHeights[0], { expires: 7, path: '/', domain: '', secure: false });
 $('#' + ContentBoxId).css({
 'line-height': AllLineHeights[0] + LineCssSizeUnits
 });
 } else {
 $('#' + ContentBoxId).css({
 'line-height': $.cookie('lineheight_' + UniqueCookieName) + LineCssSizeUnits
 });
 }
 
 $('#' + LineHeightButton).click(function(){
 var CurrentLineHeight = parseFloat(AllLineHeights.indexOf($.cookie('lineheight_' + UniqueCookieName))) + parseFloat(1);
 if(CurrentLineHeight == AllLineHeights.length) {
 NewLineHeight = AllLineHeights[0];
 } else {
 NewLineHeight = AllLineHeights[CurrentLineHeight];
 }
 $.cookie('lineheight_' + UniqueCookieName, NewLineHeight, { expires: 7, path: '/', domain: '', secure: false });
 $('#' + ContentBoxId).css({
 'line-height': NewLineHeight + LineCssSizeUnits
 });
 return false;
 });

 // Print
 $('#' + PrintButton).click(function(){
 print();
 return false;
 });

});
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);
// DONE: image description rollover
// DONE: thumbnail gallery
// DONE: IE Naviagtion fix
// DONE: window.onresize element reposition
// TODO: window scroll - gallery must be centered

/**
 * Generic popover gallery
 */
(function($) {

 // defautl configuration
 var default_config = {
 opacity: 0.8, // overlay opacity
 data_source: '', // data script url or false for inline gallery
 
 slideshow_enabled: true, // do we have a slideshow toggle button?
 slideshow_speed: 5, // no. seconds between transitions
 slideshow_auto_start: false, // no. seconds between transitions
 
 thumbnail_preview: true, // do we have thumbnail preview?
 
 mode: 'gallery' // gallery mode - "single" image or "gallery" image
 }
 
 // actual merged configuration
 var config = Array();
 
 
 var collection = Array(); // collection of images
 var current_index = 0; // current image index
 var slideshow_interval = false; // slideshow interval handler
 
 var gallery_counter = -1;
 var current_gallery = 0;
 /**
 * constructor
 */
 $.fn.popover_gallery = function(options) {
 
 
 gallery_counter++;
 current_gallery = gallery_counter;
 config[current_gallery] = $.extend({}, default_config, options);
 
 if (typeof config[current_gallery].placeholder == "string") config_array[current_gallery].placeholder = $(config_array[current_gallery].placeholder);
 
 // build the image dataset
 
 build_dataset();
 $(window).resize(function() {
 $.fn.popover_gallery.reposition();
 });
 
 return this.each(function() {
 
 // find all links that are wrapped around an image in the placeholder element
 $(this).find("a.generic").each(function(i) {
 var temp = current_gallery;
 $(this).bind('click', function(event) {
 
 event.preventDefault();
 if (this.rel == '') {
 current_index = i;
 } else {
 current_index = parseInt(this.rel)-1;
 }
 
 $.fn.popover_gallery.open(temp);
 this.blur();
 });
 });
 }); 
 
 }
 
 /**
 * opens the popover galery 
 */
 $.fn.popover_gallery.open = function (gallery_index) {
 
 current_gallery = gallery_index;
 
 // hide object and embed
 $('object, embed').each(function() {
 
 if ($(this).css('visibility') != 'hidden') {
 $(this).data('popover_gallery', { hidden: true});
 $(this).css('visibility', 'hidden');
 }

 });
 
 
 try {
 
 // init objects and properties
 init();
 
 // opening sequence
 $("#pg_overlay").fadeIn('normal', function() {
 $("#pg_toolbox").slideDown('normal', function() {
 return;
 });
 });
 
 // attach the close event on the overlay
 $("#pg_overlay").bind('click', $.fn.popover_gallery.close);
 $("#pg_close").click($.fn.popover_gallery.close);
 
 $('#pg_loading').attr('className', 'black');

 show_image();
 
 if (config.slideshow_auto_start) {
 $.fn.popover_gallery.start_slideshow(true);
 }
 
 } catch (e) {
 // do nothing 
 return false;
 }
 }
 
 /**
 * creates all the elements needed for the UI
 */
 function init() {
 // creating transparent overlay
 if (typeof($('#pg_overlay')[0]) == 'undefined') {
 var overlay = '<div id="pg_overlay"></div>';
 $("body").append(overlay);
 
 // applying style
 $("#pg_overlay").css({
 opacity: config[current_gallery].opacity
 });
 }
 
 show_loader();
 
 // creating the toolbox
 if (typeof($('#pg_toolbox')[0]) == 'undefined') {

 var toolbox = '<div id="pg_toolbox"></div>';
 
 $("body").append(toolbox);
 
 var append_str = '<a id="pg_close" href="#"><span>Close</span></a>';
 
 if (config[current_gallery].slideshow_enabled == true && collection[current_gallery].length > 1) {
 append_str += '<div id="pg_slide">';
 append_str += '<a id="pg_play" href="#"><span>Play</span></a>';
 append_str += '<a id="pg_minus" href="#"><span>-</span></a>';
 append_str += '<span id="pg_speed">' + config[current_gallery].slideshow_speed + 's</span>';
 append_str += '<a id="pg_plus" href="#"><span>+</span></a>';
 append_str += '</div>';
 }
 
 append_str += '<div id="pg_nav">';
 if (collection[current_gallery].length > 1) {
 append_str += '<a href="#" id="pg_prev"><span> << </span></a>';
 append_str += '<a href="#" id="pg_next"><span> >> </span></a>';
 }
 append_str += '<span id="pg_index">0/0</span>';
 if (collection[current_gallery].length > 1)
 
 append_str += '</div>';
 
 $("#pg_toolbox").append(append_str);
 
 $('#pg_next').click($.fn.popover_gallery.next);
 $('#pg_prev').click($.fn.popover_gallery.prev);
 
 if (config[current_gallery].slideshow_enabled) {
 $('#pg_play').click($.fn.popover_gallery.start_slideshow);
 $('#pg_minus').click($.fn.popover_gallery.speed_down);
 $('#pg_plus').click($.fn.popover_gallery.speed_up);
 }
 
 if (config[current_gallery].thumbnail_preview && collection[current_gallery].length > 1) {
 
 $("#pg_nav").append('<div id="pg_show_thumbs"></div>');
 $("#pg_toolbox").append('<div id="pg_thumbnails"><span></span></div>');
 
 last_in_row = 10;
 if (collection[current_gallery].length>54) {
 $("#pg_thumbnails").addClass('scrollable');
 last_in_row = 9;
 }
 
 if ($.browser.msie) {
 $("#pg_thumbnails").css({ borderBottom: '1px solid'});
 }
 
 // open thumbnails list
 $("#pg_show_thumbs").mouseover(function() {
 $('#pg_thumbnails').slideDown(400);
 return false;
 });
 
 
 var pg_timer_out;
 
 // close thumbnails lisr
 $("#pg_thumbnails").mouseout(function() {
 pg_timer_out = setTimeout(function() {
 $('#pg_thumbnails').slideUp(400);
 }, 400);
 });
 
 $("#pg_thumbnails").mouseover(function() {
 clearTimeout(pg_timer_out);
 });
 
 }
 
 
 
 }
 
 $('#pg_thumbnails').empty();

 var append_string= '';
 for (i=0; i<collection[current_gallery].length;i++) {
 append_string += '<div></div>';
 }
 
 $('#pg_thumbnails').append(append_string);
 
 counter = 0;
 
 $('#pg_thumbnails div').each(function(i) {
 
 counter++;
 if ( i!=0 && counter % last_in_row == 0) {
 counter=0;
 $(this).css({marginRight: -2});
 }
 
 
 $(this).css({
 display: 'block',
 background: 'transparent url('+collection[current_gallery][i].thumbnail+') center center no-repeat',
 width: 55,
 height: 55
 })
 
 $(this).src = '';
 
 $(this).click(function() {
 $.fn.popover_gallery.set_index(i);
 });
 });
 
 if (typeof($('#pg_frame')[0]) == 'undefined') {
 content_placeholder = '<div id="pg_frame"><div id="pg_content"><img src="" alt="" title=""></img><div id="pg_desc"></div><div id="pg_desc_text"></div><div id="pg_info"></div></div></div>';
 $('body').append(content_placeholder);
 }
 
 $.fn.popover_gallery.reposition();
 
 $("#pg_thumbnails").css({
 left: 0,
 top: tb_height - 1,
 width: tb_width - 3
 });
 
 if (collection[current_gallery].length > 1) {
 $('#pg_content img').click($.fn.popover_gallery.next).css({
 cursor: 'pointer'
 });
 
 }
 
 }
 
 /**
 * reposition all elements (on window rezize / scroll??)
 */
 $.fn.popover_gallery.reposition = function() {
 // get document dimensions
 body_width = $(document).width();
 // Opera dirty fix
 if($.browser.opera) {
 body_width = $('body').width();
 }
 
 body_height = $(document).height();
 
 $("#pg_overlay").css({ height: body_height });
 
 tb_width = parseInt($("#pg_toolbox").outerWidth());
 tb_height = parseInt($("#pg_toolbox").outerHeight());
 tb_left = Math.round((body_width - tb_width)/2);
 tb_top = 50;
 
 // ~vm
 // Opera dirty fix
 if($.browser.opera) {
 tb_left = Math.round((body_width - 563)/2);
 tb_width = 563;
 $("#pg_thumbnails").css({
 'margin-top': 18
 });
 }
 
 // positioning the toolbox ~vm fix
 if (typeof(document.body.style.maxHeight) != "undefined") {
 tb_top_scrolled = tb_top;
 } else {
 tb_top_scrolled = tb_top + $(document).scrollTop();
 }
 
 $("#pg_toolbox").css({
 left: tb_left,
 top: tb_top_scrolled
 });
 
 frame_width = $('#pg_frame').width();
 frame_height = $('#pg_frame').height();
 
 // position: the frame
 frame_left = (body_width/2) - (frame_width/2);
 frame_top = $(document).scrollTop() + Math.round(($(window).height() - frame_height)/2);
 
 if($.browser.opera) {
 frame_top = $('body').scrollTop() + Math.round(($(window).height() - frame_height)/2);
 }
 
 $('#pg_frame').css({
 width: frame_width,
 height: frame_height,
 left: frame_left,
 top: frame_top
 });
 
 // IE 7 hack
 // Ce ni IE6, pozicioniraj fixed
 if (typeof document.body.style.maxHeight != "undefined") {
 $('#pg_frame').css({ position: 'fixed' });
 $('#pg_toolbox').css({ position: 'fixed' });
 } else {
 $(window).one('scroll', $.fn.popover_gallery.reposition);
 }

 }
 
 /**
 * closes the gallery and removes everything.
 */
 $.fn.popover_gallery.close = function(event) {
 try {
 event.preventDefault();
 clearInterval(slideshow_interval);
 } catch (e) {}
 
 
 
 $("#pg_overlay").unbind('click');
 
 $("#pg_toolbox, #pg_loading, #pg_frame, #pg_overlay").fadeOut('fast', function() {
 current_index = 0;
 });
 
 $('object, embed').each(function() {
 
 if($(this).data('popover_gallery') && $(this).data('popover_gallery').hidden === true) {
 $(this).css('visibility', 'visible');
 $(this).data('popover_gallery', {hidden: false});
 }
 });
 }
 
 /**
 * make an ajax call to the server to get the image array
 */
 function build_dataset(params) {

 // inline gallery
 if (!config[current_gallery].data_source) {
 // return false;
 } else {
 
 $.ajax({
 cache: true,
 type: 'POST',
 url: config[current_gallery].data_source,
 data: {
 popover_gallery: 1,
 size: config[current_gallery].thumbnail_size,
 gallery_index: current_gallery
 },
 dataType: 'json',
 success: function(result) {
 // server returned json array of objects
 collection[result[0].gallery_index] = result;
 },
 error: function(obj, status, error) {
 }
 });
 }
 }
 
 // starts the slideshow
 $.fn.popover_gallery.start_slideshow = function(event) { 
 try {
 event.preventDefault();
 } catch (e) {}
 
 // ui update
 $("#pg_play").blur();
 $("#pg_play").unbind('click');
 $("#pg_play").bind('click', $.fn.popover_gallery.stop_slideshow);
 $("#pg_play").addClass('started');
 
 // refresh the interval time
 if (slideshow_interval) clearInterval(slideshow_interval);
 // run slidehow
 slideshow_interval = setInterval($.fn.popover_gallery.next, config[current_gallery].slideshow_speed * 1000);
 }
 
 // show next image
 $.fn.popover_gallery.next = function(event) {
 try {
 if (this!=window) {
 this.blur();
 event.preventDefault();
 }
 } catch (e) {}
 current_index++;
 if (current_index >= collection[current_gallery].length) current_index = 0;
 show_image();
 }
 
 // show previous image
 $.fn.popover_gallery.prev = function(event) {
 try {
 event.preventDefault();
 } catch (e) {}
 
 $("#pg_minus").blur();
 
 current_index--;
 
 if (current_index < 0) current_index = collection[current_gallery].length-1;
 
 show_image();
 }
 
 // set the current image index
 $.fn.popover_gallery.set_index = function (num) {
 current_index = num;
 show_image();
 }
 
 // increase slideshow speed
 $.fn.popover_gallery.speed_up = function(event) {
 try {
 event.preventDefault();
 } catch (e) {}
 
 $("#pg_plus").blur();
 
 config[current_gallery].slideshow_speed = config[current_gallery].slideshow_speed + 1;
 if (config[current_gallery].slideshow_speed > 15) 
 config[current_gallery].slideshow_speed = 15;
 
 $('#pg_speed').html(config[current_gallery].slideshow_speed + 's');

 $.fn.popover_gallery.start_slideshow();
 }
 
 // decrease slideshow speed
 $.fn.popover_gallery.speed_down = function(event) {
 try {
 this.blur();
 event.preventDefault();
 } catch (e) {
 
 }
 
 config[current_gallery].slideshow_speed = config[current_gallery].slideshow_speed - 1;
 if (config[current_gallery].slideshow_speed < 1) 
 config[current_gallery].slideshow_speed = 1;
 
 $('#pg_speed').html(config[current_gallery].slideshow_speed + 's');
 
 $.fn.popover_gallery.start_slideshow();
 }
 
 
 
 // stops the slideshow
 $.fn.popover_gallery.stop_slideshow = function(event) {
 try {
 event.preventDefault();
 } catch (e) {}
 
 $("#pg_play").blur();
 $("#pg_play").removeClass('started');
 $("#pg_play").unbind('click');
 $("#pg_play").bind('click' ,$.fn.popover_gallery.start_slideshow);
 
 if (slideshow_interval != false) {
 clearInterval(slideshow_interval);
 slideshow_interval = false;
 }
 }
 
 /**
 * load and show the current image
 */
 function show_image() {

 if (config[current_gallery].thumbnail_preview == true) {
 $('#pg_thumbnails').slideUp(300);
 }
 
 $('#pg_content').hide();
 
 show_loader();
 
 current_image = collection[current_gallery][current_index];
 
 tmp_img = new Image();
 tmp_img.onload = function() {
 frame_width = this.width + 50;
 frame_height = this.height + 50;
 
 // position: the frame
 frame_left = ($(document).width()/2) - (frame_width/2);
 
 if($.browser.opera) {
 frame_left = ($('body').width()/2) - (frame_width/2);
 }
 
 frame_top = Math.round(($(window).height() - frame_height)/2);
 if (!(typeof document.body.style.maxHeight != "undefined")) {
 frame_top += $(document).scrollTop();
 }
 
 // we do not have the main frame visible, lets make it (first time use)
 if ($('#pg_frame').css('display') != 'block') {
 $('#pg_frame').css({
 width: frame_width,
 height: frame_height,
 left: frame_left,
 top: frame_top
 });
 } else { // frame is allready present! just resize and display the content
 $('#pg_frame').animate({
 width: frame_width,
 height: frame_height,
 left: frame_left,
 top: frame_top
 }, 500);
 }
 
 $('#pg_content img').attr('src', tmp_img.src);
 
 hide_loader();
 
 $('#pg_index').html((current_index+1) + "/" + collection[current_gallery].length);
 
 
 $('#pg_btn_info').unbind('mouseover');
 $('#pg_btn_info').unbind('mouseout');
 $('#pg_info').empty()
 if (current_image.title != '') {
 $('#pg_info').append('<span>' + current_image.title + '</span>');
 }
 
 if (current_image.description != '') {
 
 $('#pg_desc, #pg_desc_text').empty().html('<div>' + current_image.description + '</div>').css({
 position: 'absolute',
 left: -5000,
 bottom: ($.browser.msie) ? 25 : 0,
 opacity: 0.7,
 height: 'auto',
 width: this.width
 });
 
 // IE layout fix 
 if ($.browser.msie){ 
 $("#pg_info").css({bottom:0});
 }
 
 $('#pg_desc_text').css({
 opacity: 1,
 left: -5000
 });
 
 $('#pg_info').append('<a href="#" id="pg_btn_info"><span>info</span></a>');
 
 $('#pg_btn_info').click(function() {
 return false;
 });
 } else {
 // IE layout fix 
 if ($.browser.msie){ 
 $("#pg_info").css({bottom:0});
 }
 }
 
 $('#pg_frame').fadeIn('normal', function() {
 $('#pg_content').fadeIn('fast', function() {
 
 // get tje height of the desctiption box while visible
 tmp_height = $('#pg_desc').height();
 
 $('#pg_desc, #pg_desc_text').css({
 left: 25,
 height: 0,
 display: 'none'
 });
 
 // handle the mouse events on info button
 $('#pg_btn_info').hover(
 function() {
 $('#pg_desc, #pg_desc_text').css({display: 'block'})
 $('#pg_desc, #pg_desc_text').animate({
 height: tmp_height
 }, 400);
 },
 function() {
 $('#pg_desc, #pg_desc_text').animate({
 height: 0
 }, 400, function() {
 $('#pg_desc, #pg_desc_text').css({display: 'none'})
 })
 }
 );
 });
 
 });
 }
 
 tmp_img.src = current_image.picture;
 }
 
 /**
 * shows the loading animation
 */
 function show_loader() {
 
 // creating loading animation if not present
 if (typeof($('#pg_loading')[0]) == 'undefined') {
 $('body').append('<div id="pg_loading"></div>');
 }
 
 loader_w = $('#pg_loading').outerWidth();
 loader_h = $('#pg_loading').outerHeight();
 
 loader_l = Math.round(($(document).width() - loader_w)/2);
 
 if($.browser.opera) {
 loader_l = Math.round(($('body').width() - loader_w)/2);
 }
 
 loader_t = $(document).scrollTop() + Math.round(($(window).height() - loader_h)/2);
 
 $('#pg_loading').css({
 left: loader_l,
 top: loader_t,
 zIndex: 1000
 });
 
 $('#pg_loading').fadeIn('normal');
 }
 
 /**
 * hides the loading animation
 */
 function hide_loader() {
 $('#pg_loading').fadeOut('normal');
 }
 
 //-----------------------------------------------------

 /**
 * simple firebug debug function
 */
 function debug(param) {
 
 if (typeof(param) == "object") {
 output = 'OBJECT\n';
 for ( a in param) {
 output += "\t" + a + ": " + param[a] + "\n"; 
 }
 
 param = output;
 }
 
 if (window.console && window.console.log) {
 window.console.log('[generic_gallery] '+ param);
 } else {
 //alert(param);
 }
 };

})(jQuery);



/**
 * Copyright (c) 2009 Anders Ekdahl (http://coffeescripter.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.2.2
 *
 * Demo and documentation: http://coffeescripter.com/code/ad-gallery/
 */
(function($) {
 $.fn.adGallery = function(options) {
 var defaults = { loader_image: 'loader.gif',
 start_at_index: 0,
 thumb_opacity: 0.7,
 animate_first_image: false,
 animation_speed: 400,
 width: false,
 height: false,
 display_next_and_prev: true,
 display_back_and_forward: true,
 scroll_jump: 0, // If 0, it jumps the width of the container
 slideshow: {
 enable: false,
 autostart: false,
 speed: 5000,
 start_label: 'Start',
 stop_label: 'Stop',
 stop_on_scroll: true,
 countdown_prefix: '(',
 countdown_sufix: ')',
 onStart: false,
 onStop: false
 },
 effect: 'fade', // or 'slide-hori' 'slide-vert', 'fade', or 'resize', 'none'
 enable_keyboard_move: true,
 cycle: true,
 callbacks: {
 init: false,
 afterImageVisible: false,
 beforeImageVisible: false
 }
 };
 var settings = $.extend(false, defaults, options);
 if(options && options.slideshow) {
 settings.slideshow = $.extend(false, defaults.slideshow, options.slideshow);
 };
 if(!settings.slideshow.enable) {
 settings.slideshow.autostart = false;
 };
 var galleries = [];
 $(this).each(function() {
 var gallery = new AdGallery(this, settings);
 galleries[galleries.length] = gallery;
 });
 // Sorry, breaking the jQuery chain because the gallery instances
 // are returned so you can fiddle with them
 return galleries;
 };

 function VerticalSlideAnimation(img_container, direction, desc) {
 var current_top = parseInt(img_container.css('top'), 10);
 if(direction == 'left') {
 var old_image_top = '-'+ this.image_wrapper_height +'px';
 img_container.css('top', this.image_wrapper_height +'px');
 } else {
 var old_image_top = this.image_wrapper_height +'px';
 img_container.css('top', '-'+ this.image_wrapper_height +'px');
 };
 if(desc) {
 desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
 desc.animate({bottom: 0}, this.settings.animation_speed * 2);
 };
 return {old_image: {top: old_image_top},
 new_image: {top: current_top}};
 };

 function HorizontalSlideAnimation(img_container, direction, desc) {
 var current_left = parseInt(img_container.css('left'), 10);
 if(direction == 'left') {
 var old_image_left = '-'+ this.image_wrapper_width +'px';
 img_container.css('left',this.image_wrapper_width +'px');
 } else {
 var old_image_left = this.image_wrapper_width +'px';
 img_container.css('left','-'+ this.image_wrapper_width +'px');
 };
 if(desc) {
 desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
 desc.animate({bottom: 0}, this.settings.animation_speed * 2);
 };
 return {old_image: {left: old_image_left},
 new_image: {left: current_left}};
 };

 function ResizeAnimation(img_container, direction, desc) {
 var image_width = img_container.width();
 var image_height = img_container.height();
 var current_left = parseInt(img_container.css('left'), 10);
 var current_top = parseInt(img_container.css('top'), 10);
 img_container.css({width: 0, height: 0, top: this.image_wrapper_height / 2, left: this.image_wrapper_width / 2});
 return {old_image: {width: 0,
 height: 0,
 top: this.image_wrapper_height / 2,
 left: this.image_wrapper_width / 2},
 new_image: {width: image_width,
 height: image_height,
 top: current_top,
 left: current_left}};
 };

 function FadeAnimation(img_container, direction, desc) {
 img_container.css('opacity', 0);
 return {old_image: {opacity: 0},
 new_image: {opacity: 1}};
 };

 // Sort of a hack, will clean this up... eventually
 function NoneAnimation(img_container, direction, desc) {
 img_container.css('opacity', 0);
 return {old_image: {opacity: 0},
 new_image: {opacity: 1},
 speed: 0};
 };

 function AdGallery(wrapper, settings) {
 this.init(wrapper, settings);
 };
 AdGallery.prototype = {
 // Elements
 wrapper: false,
 image_wrapper: false,
 gallery_info: false,
 nav: false,
 loader: false,
 preloads: false,
 thumbs_wrapper: false,
 scroll_back: false,
 scroll_forward: false,
 next_link: false,
 prev_link: false,

 slideshow: false,
 image_wrapper_width: 0,
 image_wrapper_height: 0,
 current_index: 0,
 current_image: false,
 nav_display_width: 0,
 settings: false,
 images: false,
 in_transition: false,
 animations: false,
 init: function(wrapper, settings) {
 var context = this;
 this.wrapper = $(wrapper);
 this.settings = settings;
 this.setupElements();
 this.setupAnimations();
 if(this.settings.width) {
 this.image_wrapper_width = this.settings.width;
 this.image_wrapper.width(this.settings.width);
 this.wrapper.width(this.settings.width);
 } else {
 this.image_wrapper_width = this.image_wrapper.width();
 };
 if(this.settings.height) {
 this.image_wrapper_height = this.settings.height;
 this.image_wrapper.height(this.settings.height);
 } else {
 this.image_wrapper_height = this.image_wrapper.height();
 };
 this.nav_display_width = this.nav.width();
 this.current_index = 0;
 this.current_image = false;
 this.in_transition = false;
 this.findImages();
 if(this.settings.display_next_and_prev) {
 this.initNextAndPrev();
 };
 // The slideshow needs a callback to trigger the next image to be shown
 // but we don't want to give it access to the whole gallery instance
 var nextimage_callback = function(callback) {
 return context.nextImage(callback);
 };
 this.slideshow = new AdGallerySlideshow(nextimage_callback, this.settings.slideshow);
 this.controls.append(this.slideshow.create());
 if(this.settings.slideshow.enable) {
 this.slideshow.enable();
 } else {
 this.slideshow.disable();
 };
 if(this.settings.display_back_and_forward) {
 this.initBackAndForward();
 };
 if(this.settings.enable_keyboard_move) {
 this.initKeyEvents();
 };
 var start_at = this.settings.start_at_index;
 if(window.location.hash && window.location.hash.indexOf('#ad-image') === 0) {
 start_at = window.location.hash.replace(/[^0-9]+/g, '');
 // Check if it's a number
 if((start_at * 1) != start_at) {
 start_at = this.settings.start_at_index;
 };
 };

 this.loading(true);
 this.showImage(start_at,
 function() {
 // We don't want to start the slideshow before the image has been
 // displayed
 if(context.settings.slideshow.autostart) {
 context.preloadImage(start_at + 1);
 context.slideshow.start();
 };
 }
 );
 this.fireCallback(this.settings.callbacks.init);
 },
 setupAnimations: function() {
 this.animations = {
 'slide-vert': VerticalSlideAnimation,
 'slide-hori': HorizontalSlideAnimation,
 'resize': ResizeAnimation,
 'fade': FadeAnimation,
 'none': NoneAnimation
 };
 },
 setupElements: function() {
 this.controls = this.wrapper.find('.ad-controls');
 this.gallery_info = $('<p class="ad-info"></p>');
 this.controls.append(this.gallery_info);
 this.image_wrapper = this.wrapper.find('.ad-image-wrapper');
 this.image_wrapper.empty();
 this.nav = this.wrapper.find('.ad-nav');
 this.thumbs_wrapper = this.nav.find('.ad-thumbs');
 this.preloads = $('<div class="ad-preloads"></div>');
 this.loader = $('<img class="ad-loader" src="'+ this.settings.loader_image +'">');
 this.image_wrapper.append(this.loader);
 this.loader.hide();
 $(document.body).append(this.preloads);
 },
 loading: function(bool) {
 if(bool) {
 this.loader.show();
 } else {
 this.loader.hide();
 };
 },
 addAnimation: function(name, fn) {
 if($.isFunction(fn)) {
 this.animations[name] = fn;
 };
 },
 findImages: function() {
 var context = this;
 this.images = [];
 var thumb_wrapper_width = 0;
 var thumbs_loaded = 0;
 var thumbs = this.thumbs_wrapper.find('a');
 var thumb_count = thumbs.length;
 if(this.settings.thumb_opacity < 1) {
 thumbs.find('img').css('opacity', this.settings.thumb_opacity);
 };
 thumbs.each(
 function(i) {
 var link = $(this);
 var image_src = link.attr('href');
 var thumb = link.find('img');
 // Check if the thumb has already loaded
 if(!context.isImageLoaded(thumb[0])) {
 thumb.load(
 function() {
 thumb_wrapper_width += this.parentNode.parentNode.offsetWidth;
 thumbs_loaded++;
 }
 );
 } else{
 thumb_wrapper_width += thumb[0].parentNode.parentNode.offsetWidth;
 thumbs_loaded++;
 };
 link.addClass('ad-thumb'+ i);
 link.click(
 function() {
 context.showImage(i);
 context.slideshow.stop();
 return false;
 }
 ).hover(
 function() {
 if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
 $(this).find('img').fadeTo(300, 1);
 };
 context.preloadImage(i);
 },
 function() {
 if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
 $(this).find('img').fadeTo(300, context.settings.thumb_opacity);
 };
 }
 );
 var desc = false;
 if(thumb.data('ad-desc')) {
 desc = thumb.data('ad-desc');
 } else if(thumb.attr('longdesc') && thumb.attr('longdesc').length) {
 desc = thumb.attr('longdesc');
 };
 var title = false;
 if(thumb.data('ad-title')) {
 title = thumb.data('ad-title');
 } else if(thumb.attr('title') && thumb.attr('title').length) {
 title = thumb.attr('title');
 };
 context.images[i] = { thumb: thumb.attr('src'), image: image_src, error: false,
 preloaded: false, desc: desc, title: title, size: false };
 }
 );
 // Wait until all thumbs are loaded, and then set the width of the ul
 var inter = setInterval(
 function() {
 if(thumb_count == thumbs_loaded) {
 context.nav.find('.ad-thumb-list').css('width', thumb_wrapper_width +'px');
 clearInterval(inter);
 };
 },
 100
 );
 },
 initKeyEvents: function() {
 var context = this;
 $(document).keydown(
 function(e) {
 if(e.keyCode == 39) {
 // right arrow
 context.nextImage();
 context.slideshow.stop();
 } else if(e.keyCode == 37) {
 // left arrow
 context.prevImage();
 context.slideshow.stop();
 };
 }
 );
 },
 initNextAndPrev: function() {
 this.next_link = $('<div class="ad-next"><div class="ad-next-image"></div></div>');
 this.prev_link = $('<div class="ad-prev"><div class="ad-prev-image"></div></div>');
 this.image_wrapper.append(this.next_link);
 this.image_wrapper.append(this.prev_link);
 var context = this;
 this.prev_link.add(this.next_link).mouseover(
 function(e) {
 // IE 6 hides the wrapper div, so we have to set it's width
 $(this).css('height', context.image_wrapper_height);
 $(this).find('div').show();
 }
 ).mouseout(
 function(e) {
 $(this).find('div').hide();
 }
 ).click(
 function() {
 if($(this).is('.ad-next')) {
 context.nextImage();
 context.slideshow.stop();
 } else {
 context.prevImage();
 context.slideshow.stop();
 };
 }
 ).find('div').css('opacity', 0.7);
 },
 initBackAndForward: function() {
 var context = this;
 this.scroll_forward = $('<div class="ad-forward"></div>');
 this.scroll_back = $('<div class="ad-back"></div>');
 this.nav.append(this.scroll_forward);
 this.nav.prepend(this.scroll_back);
 var has_scrolled = 0;
 var thumbs_scroll_interval = false;
 $(this.scroll_back).add(this.scroll_forward).click(
 function() {
 // We don't want to jump the whole width, since an image
 // might be cut at the edge
 var width = context.nav_display_width - 50;
 if(context.settings.scroll_jump > 0) {
 var width = context.settings.scroll_jump;
 };
 if($(this).is('.ad-forward')) {
 var left = context.thumbs_wrapper.scrollLeft() + width;
 } else {
 var left = context.thumbs_wrapper.scrollLeft() - width;
 };
 if(context.settings.slideshow.stop_on_scroll) {
 context.slideshow.stop();
 };
 context.thumbs_wrapper.animate({scrollLeft: left +'px'});
 return false;
 }
 ).css('opacity', 0.6).hover(
 function() {
 var direction = 'left';
 if($(this).is('.ad-forward')) {
 direction = 'right';
 };
 thumbs_scroll_interval = setInterval(
 function() {
 has_scrolled++;
 // Don't want to stop the slideshow just because we scrolled a pixel or two
 if(has_scrolled > 30 && context.settings.slideshow.stop_on_scroll) {
 context.slideshow.stop();
 };
 var left = context.thumbs_wrapper.scrollLeft() + 1;
 if(direction == 'left') {
 left = context.thumbs_wrapper.scrollLeft() - 1;
 };
 context.thumbs_wrapper.scrollLeft(left);
 },
 10
 );
 $(this).css('opacity', 1);
 },
 function() {
 has_scrolled = 0;
 clearInterval(thumbs_scroll_interval);
 $(this).css('opacity', 0.6);
 }
 );
 },
 _afterShow: function() {
 this.gallery_info.html((this.current_index + 1) +' / '+ this.images.length);
 if(!this.settings.cycle) {
 // Needed for IE
 this.prev_link.show().css('height', this.image_wrapper_height);
 this.next_link.show().css('height', this.image_wrapper_height);
 if(this.current_index == (this.images.length - 1)) {
 this.next_link.hide();
 };
 if(this.current_index == 0) {
 this.prev_link.hide();
 };
 };
 this.fireCallback(this.settings.callbacks.afterImageVisible);
 },
 /**
 * Checks if the image is small enough to fit inside the container
 * If it's not, shrink it proportionally
 */
 _getContainedImageSize: function(image_width, image_height) {
 if(image_height > this.image_wrapper_height) {
 var ratio = image_width / image_height;
 image_height = this.image_wrapper_height;
 image_width = this.image_wrapper_height * ratio;
 };
 if(image_width > this.image_wrapper_width) {
 var ratio = image_height / image_width;
 image_width = this.image_wrapper_width;
 image_height = this.image_wrapper_width * ratio;
 };
 return {width: image_width, height: image_height};
 },
 /**
 * If the image dimensions are smaller than the wrapper, we position
 * it in the middle anyway
 */
 _centerImage: function(img_container, image_width, image_height) {
 img_container.css('top', '0px');
 if(image_height < this.image_wrapper_height) {
 var dif = this.image_wrapper_height - image_height;
 img_container.css('top', (dif / 2) +'px');
 };
 img_container.css('left', '0px');
 if(image_width < this.image_wrapper_width) {
 var dif = this.image_wrapper_width - image_width;
 img_container.css('left', (dif / 2) +'px');
 };
 },
 _getDescription: function(image) {
 var desc = false;
 if(image.desc.length || image.title.length) {
 var title = '';
 if(image.title.length) {
 title = '<strong class="ad-description-title">'+ image.title +'</strong>';
 };
 var desc = '';
 if(image.desc.length) {
 desc = '<span>'+ image.desc +'</span>';
 };
 desc = $('<p class="ad-image-description">'+ title + desc +'</p>');
 };
 return desc;
 },
 /**
 * @param function callback Gets fired when the image has loaded, is displaying
 * and it's animation has finished
 */
 showImage: function(index, callback) {
 if(this.images[index] && !this.in_transition) {
 var context = this;
 var image = this.images[index];
 this.in_transition = true;
 if(!image.preloaded) {
 this.loading(true);
 this.preloadImage(index, function() {
 context.loading(false);
 context._showWhenLoaded(index, callback);
 });
 } else {
 this._showWhenLoaded(index, callback);
 };
 };
 },
 /**
 * @param function callback Gets fired when the image has loaded, is displaying
 * and it's animation has finished
 */
 _showWhenLoaded: function(index, callback) {
 if(this.images[index]) {
 var context = this;
 var image = this.images[index];
 var img_container = $(document.createElement('div')).addClass('ad-image');
 var img = $(new Image()).attr('src', image.image);
 img_container.append(img);
 this.image_wrapper.prepend(img_container);
 var size = this._getContainedImageSize(image.size.width, image.size.height);
 img.attr('width', size.width);
 img.attr('height', size.height);
 img_container.css({width: size.width +'px', height: size.height +'px'});
 this._centerImage(img_container, size.width, size.height);
 var desc = this._getDescription(image, img_container);
 if(desc) {
 img_container.append(desc);
 var width = size.width - parseInt(desc.css('padding-left'), 10) - parseInt(desc.css('padding-right'), 10);
 desc.css('width', width +'px');
 };
 this.highLightThumb(this.nav.find('.ad-thumb'+ index));

 var direction = 'right';
 if(this.current_index < index) {
 direction = 'left';
 };
 this.fireCallback(this.settings.callbacks.beforeImageVisible);
 if(this.current_image || this.settings.animate_first_image) {
 var animation_speed = this.settings.animation_speed;
 var easing = 'swing';
 var animation = this.animations[this.settings.effect].call(this, img_container, direction, desc);
 if(typeof animation.speed != 'undefined') {
 animation_speed = animation.speed;
 };
 if(typeof animation.easing != 'undefined') {
 easing = animation.easing;
 };
 if(this.current_image) {
 var old_image = this.current_image;
 old_image.animate(animation.old_image, animation_speed, easing,
 function() {
 old_image.remove();
 }
 );
 };
 img_container.animate(animation.new_image, animation_speed, easing,
 function() {
 context.current_index = index;
 context.current_image = img_container;
 context.in_transition = false;
 context._afterShow();
 context.fireCallback(callback);
 }
 );
 } else {
 this.current_index = index;
 this.current_image = img_container;
 this.in_transition = false;
 context._afterShow();
 this.fireCallback(callback);
 };
 };
 },
 nextIndex: function() {
 if(this.current_index == (this.images.length - 1)) {
 if(!this.settings.cycle) {
 return false;
 };
 var next = 0;
 } else {
 var next = this.current_index + 1;
 };
 return next;
 },
 nextImage: function(callback) {
 var next = this.nextIndex();
 if(next === false) return false;
 this.preloadImage(next + 1);
 this.showImage(next, callback);
 return true;
 },
 prevIndex: function() {
 if(this.current_index == 0) {
 if(!this.settings.cycle) {
 return false;
 };
 var prev = this.images.length - 1;
 } else {
 var prev = this.current_index - 1;
 };
 return prev;
 },
 prevImage: function(callback) {
 var prev = this.prevIndex();
 if(prev === false) return false;
 this.preloadImage(prev - 1);
 this.showImage(prev, callback);
 return true;
 },
 preloadAll: function() {
 var context = this;
 var i = 0;
 function preloadNext() {
 if(i < context.images.length) {
 i++;
 context.preloadImage(i, preloadNext);
 };
 };
 context.preloadImage(i, preloadNext);
 },
 preloadImage: function(index, callback) {
 if(this.images[index]) {
 var image = this.images[index];
 if(!this.images[index].preloaded) {
 var img = $(new Image());
 img.attr('src', image.image);
 if(!this.isImageLoaded(img[0])) {
 this.preloads.append(img);
 var context = this;
 img.load(
 function() {
 image.preloaded = true;
 image.size = { width: this.width, height: this.height };
 context.fireCallback(callback);
 }
 ).error(
 function() {
 image.error = true;
 image.preloaded = false;
 image.size = false;
 }
 );
 } else {
 image.preloaded = true;
 image.size = { width: img[0].width, height: img[0].height };
 this.fireCallback(callback);
 };
 } else {
 this.fireCallback(callback);
 };
 };
 },
 isImageLoaded: function(img) {
 if(typeof img.complete != 'undefined' && !img.complete) {
 return false;
 };
 if(typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
 return false;
 };
 return true;
 },
 highLightThumb: function(thumb) {
 this.thumbs_wrapper.find('.ad-active').removeClass('ad-active');
 thumb.addClass('ad-active');
 if(this.settings.thumb_opacity < 1) {
 this.thumbs_wrapper.find('a:not(.ad-active) img').fadeTo(300, this.settings.thumb_opacity);
 thumb.find('img').fadeTo(300, 1);
 };
 var left = thumb[0].parentNode.offsetLeft;
 left -= (this.nav_display_width / 2) - (thumb[0].offsetWidth / 2);
 this.thumbs_wrapper.animate({scrollLeft: left +'px'});
 },
 fireCallback: function(fn) {
 if($.isFunction(fn)) {
 fn.call(this);
 };
 }
 };

 function AdGallerySlideshow(nextimage_callback, settings) {
 this.init(nextimage_callback, settings);
 };
 AdGallerySlideshow.prototype = {
 start_link: false,
 stop_link: false,
 countdown: false,
 controls: false,

 settings: false,
 nextimage_callback: false,
 enabled: false,
 running: false,
 countdown_interval: false,
 init: function(nextimage_callback, settings) {
 var context = this;
 this.nextimage_callback = nextimage_callback;
 this.settings = settings;
 },
 create: function() {
 this.start_link = $('<span class="ad-slideshow-start">'+ this.settings.start_label +'</span>');
 this.stop_link = $('<span class="ad-slideshow-stop">'+ this.settings.stop_label +'</span>');
 this.countdown = $('<span class="ad-slideshow-countdown"></span>');
 this.controls = $('<div class="ad-slideshow-controls"></div>');
 this.controls.append(this.start_link).append(this.stop_link).append(this.countdown);
 this.countdown.hide();

 var context = this;
 this.start_link.click(
 function() {
 context.start();
 }
 );
 this.stop_link.click(
 function() {
 context.stop();
 }
 );
 $(document).keydown(
 function(e) {
 if(e.keyCode == 83) {
 // 's'
 if(context.running) {
 context.stop();
 } else {
 context.start();
 };
 };
 }
 );
 return this.controls;
 },
 disable: function() {
 this.enabled = false;
 this.stop();
 this.controls.hide();
 },
 enable: function() {
 this.enabled = true;
 this.controls.show();
 },
 toggle: function() {
 if(this.enabled) {
 this.disable();
 } else {
 this.enable();
 };
 },
 start: function() {
 if(this.running || !this.enabled) return false;
 var context = this;
 this.running = true;
 this.controls.addClass('ad-slideshow-running');
 this._next();
 this.fireCallback(this.settings.onStart);
 return true;
 },
 stop: function() {
 if(!this.running) return false;
 this.running = false;
 this.countdown.hide();
 this.controls.removeClass('ad-slideshow-running');
 clearInterval(this.countdown_interval);
 this.fireCallback(this.settings.onStop);
 return true;
 },
 _next: function() {
 var context = this;
 var pre = this.settings.countdown_prefix;
 var su = this.settings.countdown_sufix;
 clearInterval(context.countdown_interval);
 this.countdown.show().html(pre + (this.settings.speed / 1000) + su);
 var slide_timer = 0;
 this.countdown_interval = setInterval(
 function() {
 slide_timer += 1000;
 if(slide_timer >= context.settings.speed) {
 var whenNextIsShown = function() {
 // A check so the user hasn't stoped the slideshow during the
 // animation
 if(context.running) {
 context._next();
 };
 slide_timer = 0;
 };
 if(!context.nextimage_callback(whenNextIsShown)) {
 context.stop();
 };
 slide_timer = 0;
 };
 var sec = parseInt(context.countdown.text().replace(/[^0-9]/g, ''), 10);
 sec--;
 if(sec > 0) {
 context.countdown.html(pre + sec + su);
 };
 },
 1000
 );
 },
 fireCallback: function(fn) {
 if($.isFunction(fn)) {
 fn.call(this);
 };
 }
 };
})(jQuery);





(function ($) {

 /**********************************
 * CUSTOMIZE THE DEFAULT SETTINGS
 * Ex:
 * var _settings = {
 * id: 'modal',
 * src: function(sender){
 * return jQuery(sender).attr('href');
 * },
 * width: 800,
 * height: 600
 * }
 **********************************/
 var _settings = {
 width: 800, // Use this value if not set in CSS or HTML
 height: 600, // Use this value if not set in CSS or HTML
 overlayOpacity: .85, // Use this value if not set in CSS or HTML
 id: 'modal',
 modalClassName: 'modal-p-window',
 imageClassName: 'modal-p-image',
 closeClassName: 'close-p-window',
 overlayClassName: 'modal-p-overlay',
 src: 'popover_video.php',
 //src: function (sender) {
 // return jQuery(sender).attr('href');
 //},
 fadeInSpeed: 0,
 fadeOutSpeed: 0
 }

 /**********************************
 * DO NOT CUSTOMIZE BELOW THIS LINE
 **********************************/
 $.modal = function (options) {
 return _modal(this, options);
 }
 $.modal.open = function () {
 _modal.open();
 }
 $.modal.close = function () {
 _modal.close();
 }
 $.fn.modal = function (options) {
 return _modal(this, options);
 }
 _modal = function (sender, params) {
 this.options = {
 parent: null,
 overlayOpacity: null,
 id: null,
 content: null,
 width: null,
 height: null,
 modalClassName: null,
 imageClassName: null,
 closeClassName: null,
 overlayClassName: null,
 src: null
 }
 this.options = $.extend({}, options, _defaults);
 this.options = $.extend({}, options, _settings);
 this.options = $.extend({}, options, params);
 this.close = function () {
 jQuery('.' + options.modalClassName + ', .' + options.overlayClassName).fadeOut(_settings.fadeOutSpeed, function () { jQuery(this).unbind().remove(); });
 }
 this.open = function () {
 if (typeof options.src == 'function') {
 options.src = options.src(sender)
 } else {
 options.src = options.src || _defaults.src(sender);
 }

 var fileExt = /^.+\.((jpg)|(gif)|(jpeg)|(png)|(jpg))$/i;
 var contentHTML = '';
 if (fileExt.test(options.src)) {
 contentHTML = '<div class="' + options.imageClassName + '"><img src="' + options.src + '"/></div>';

 } else {
 contentHTML = '<iframe width="' + options.width + '" height="' + options.height + '" frameborder="0" scrolling="no" allowtransparency="true" src="' + options.src + '"></iframe>';
 }
 options.content = options.content || contentHTML;

 if (jQuery('.' + options.modalClassName).length && jQuery('.' + options.overlayClassName).length) {
 jQuery('.' + options.modalClassName).html(options.content);
 } else {
 $overlay = jQuery((_isIE6()) ? '<iframe src="BLOCKED SCRIPT\'<html></html>\';" scrolling="no" frameborder="0" class="' + options.overlayClassName + '"></iframe><div class="' + options.overlayClassName + '"></div>' : '<div class="' + options.overlayClassName + '"></div>');
 $overlay.hide().appendTo(options.parent);

 $modal = jQuery('<div id="' + options.id + '" class="' + options.modalClassName + '" style="width:' + options.width + 'px; height:' + options.height + 'px; margin-top:-' + (options.height / 2) + 'px; margin-left:-' + (options.width / 2) + 'px;">' + options.content + '</div>');
 $modal.hide().appendTo(options.parent);

 $close = jQuery('<a class="' + options.closeClassName + '"></a>');
 $close.appendTo($modal);

 var overlayOpacity = _getOpacity($overlay.not('iframe')) || options.overlayOpacity;
 $overlay.fadeTo(0, 0).show().not('iframe').fadeTo(_settings.fadeInSpeed, overlayOpacity);
 $modal.fadeIn(_settings.fadeInSpeed);

 $close.click(function () { jQuery.modal().close(); });
 $overlay.click(function () { jQuery.modal().close(); });
 }
 }
 return this;
 }
 _isIE6 = function () {
 if (document.all && document.getElementById) {
 if (document.compatMode && !window.XMLHttpRequest) {
 return true;
 }
 }
 return false;
 }
 _getOpacity = function (sender) {
 $sender = jQuery(sender);
 opacity = $sender.css('opacity');
 filter = $sender.css('filter');

 if (filter.indexOf("opacity=") >= 0) {
 return parseFloat(filter.match(/opacity=([^)]*)/)[1]) / 100;
 }
 else if (opacity != '') {
 return opacity;
 }
 return '';
 }
 _defaults = {
 parent: 'body',
 overlayOpacity: 85,
 id: 'modal',
 content: null,
 width: 800,
 height: 600,
 modalClassName: 'modal-window',
 imageClassName: 'modal-image',
 closeClassName: 'close-window',
 overlayClassName: 'modal-overlay',
 src: function (sender) {
 return jQuery(sender).attr('href');
 }
 }
})(jQuery);
/* SWFObject v2.2 <http://code.google.com/p/swfobject/> 
 is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated. All rights reserved.
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
 var version;
 var axo;
 var e;

 // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

 try {
 // version will be set for 7.X or greater players
 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
 version = axo.GetVariable("$version");
 } catch (e) {
 }

 if (!version)
 {
 try {
 // version will be set for 6.X players only
 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
 
 // installed player is some revision of 6.0
 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
 // so we have to be careful. 
 
 // default to the first public version
 version = "WIN 6,0,21,0";

 // throws if AllowScripAccess does not exist (introduced in 6.0r47) 
 axo.AllowScriptAccess = "always";

 // safe to call for 6.0r47 or greater
 version = axo.GetVariable("$version");

 } catch (e) {
 }
 }

 if (!version)
 {
 try {
 // version will be set for 4.X or 5.X player
 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
 version = axo.GetVariable("$version");
 } catch (e) {
 }
 }

 if (!version)
 {
 try {
 // version will be set for 3.X player
 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
 version = "WIN 3,0,18,0";
 } catch (e) {
 }
 }

 if (!version)
 {
 try {
 // version will be set for 2.X player
 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
 version = "WIN 2,0,0,11";
 } catch (e) {
 version = -1;
 }
 }
 
 return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
 // NS/Opera version >= 3 check for Flash plugin in plugin array
 var flashVer = -1;
 
 if (navigator.plugins != null && navigator.plugins.length > 0) {
 if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
 var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
 var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
 var descArray = flashDescription.split(" ");
 var tempArrayMajor = descArray[2].split("."); 
 var versionMajor = tempArrayMajor[0];
 var versionMinor = tempArrayMajor[1];
 var versionRevision = descArray[3];
 if (versionRevision == "") {
 versionRevision = descArray[4];
 }
 if (versionRevision[0] == "d") {
 versionRevision = versionRevision.substring(1);
 } else if (versionRevision[0] == "r") {
 versionRevision = versionRevision.substring(1);
 if (versionRevision.indexOf("d") > 0) {
 versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
 }
 }
 var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
 }
 }
 // MSN/WebTV 2.6 supports Flash 4
 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
 // WebTV 2.5 supports Flash 3
 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
 // older WebTV supports Flash 2
 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
 else if ( isIE && isWin && !isOpera ) {
 flashVer = ControlVersion();
 } 
 return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
 versionStr = GetSwfVer();
 if (versionStr == -1 ) {
 return false;
 } else if (versionStr != 0) {
 if(isIE && isWin && !isOpera) {
 // Given "WIN 2,0,0,11"
 tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"]
 tempString = tempArray[1]; // "2,0,0,11"
 versionArray = tempString.split(","); // ['2', '0', '0', '11']
 } else {
 versionArray = versionStr.split(".");
 }
 var versionMajor = versionArray[0];
 var versionMinor = versionArray[1];
 var versionRevision = versionArray[2];

 // is the major.revision >= requested major.revision AND the minor version >= requested minor
 if (versionMajor > parseFloat(reqMajorVer)) {
 return true;
 } else if (versionMajor == parseFloat(reqMajorVer)) {
 if (versionMinor > parseFloat(reqMinorVer))
 return true;
 else if (versionMinor == parseFloat(reqMinorVer)) {
 if (versionRevision >= parseFloat(reqRevision))
 return true;
 }
 }
 return false;
 }
}

function AC_AddExtension(src, ext)
{
 if (src.indexOf('?') != -1)
 return src.replace(/\?/, ext+'?'); 
 else
 return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
 var str = '';
 if (isIE && isWin && !isOpera)
 {
 str += '<object ';
 for (var i in objAttrs)
 {
 str += i + '="' + objAttrs[i] + '" ';
 }
 str += '>';
 for (var i in params)
 {
 str += '<param name="' + i + '" value="' + params[i] + '" /> ';
 }
 str += '</object>';
 }
 else
 {
 str += '<embed ';
 for (var i in embedAttrs)
 {
 str += i + '="' + embedAttrs[i] + '" ';
 }
 str += '> </embed>';
 }

 document.write(str);
}

function AC_FL_RunContent(){
 var ret = 
 AC_GetArgs
 ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
 , "application/x-shockwave-flash"
 );
 AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
 var ret = 
 AC_GetArgs
 ( arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
 , null
 );
 AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
 var ret = new Object();
 ret.embedAttrs = new Object();
 ret.params = new Object();
 ret.objAttrs = new Object();
 for (var i=0; i < args.length; i=i+2){
 var currArg = args[i].toLowerCase(); 

 switch (currArg){ 
 case "classid":
 break;
 case "pluginspage":
 ret.embedAttrs[args[i]] = args[i+1];
 break;
 case "src":
 case "movie": 
 args[i+1] = AC_AddExtension(args[i+1], ext);
 ret.embedAttrs["src"] = args[i+1];
 ret.params[srcParamName] = args[i+1];
 break;
 case "onafterupdate":
 case "onbeforeupdate":
 case "onblur":
 case "oncellchange":
 case "onclick":
 case "ondblclick":
 case "ondrag":
 case "ondragend":
 case "ondragenter":
 case "ondragleave":
 case "ondragover":
 case "ondrop":
 case "onfinish":
 case "onfocus":
 case "onhelp":
 case "onmousedown":
 case "onmouseup":
 case "onmouseover":
 case "onmousemove":
 case "onmouseout":
 case "onkeypress":
 case "onkeydown":
 case "onkeyup":
 case "onload":
 case "onlosecapture":
 case "onpropertychange":
 case "onreadystatechange":
 case "onrowsdelete":
 case "onrowenter":
 case "onrowexit":
 case "onrowsinserted":
 case "onstart":
 case "onscroll":
 case "onbeforeeditfocus":
 case "onactivate":
 case "onbeforedeactivate":
 case "ondeactivate":
 case "type":
 case "codebase":
 case "id":
 ret.objAttrs[args[i]] = args[i+1];
 break;
 case "width":
 case "height":
 case "align":
 case "vspace": 
 case "hspace":
 case "class":
 case "title":
 case "accesskey":
 case "name":
 case "tabindex":
 ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
 break;
 default:
 ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
 }
 }
 ret.objAttrs["classid"] = classid;
 if (mimeType) ret.embedAttrs["type"] = mimeType;
 return ret;
}

function write_swf(filename,id,width,height,extra) {
 document.write('<object type="application/x-shockwave-flash" data="'+filename+(id!=null?'?cid='+id:'')+'" width="'+width+'" height="'+height+'">');
 document.write('<param name="movie" value="'+filename+(id!=null?'?cid='+id:'')+'" />');
 
 document.write('<param name="quality" value="autohigh" />');
 document.write('<param name="wmode" value="transparent" />');
 document.write('<param name="menu" value="false" />');
 

 for (i in extra) {
 document.write('<param name="'+extra[i][0]+'" value="'+extra[i][1]+'" />');
 }
 document.write('</object>');
}


function open_legend() {
 $("#legenda").css("display","block");
}
function close_legend() {
 $("#legenda").css("display","none");
}

/*
function open_popover() {
 alert(123);
 
}
*/
function write_flash(filename, width, height, imagepath, paramstr) {
 
 
 document.write("<script type='text/javascript'>");
 document.write("AC_FL_RunContent(");
 document.write("'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',");
 document.write("'width', "+width+",");
 document.write("'height', "+height+",");
 document.write("'src', 'flash/"+filename+"',");
 document.write("'quality', 'high',");
 document.write("'pluginspage', 'http://www.macromedia.com/go/getflashplayer',");
 document.write("'align', 'middle',");
 document.write("'play', 'true',");
 document.write("'loop', 'true',");
 document.write("'scale', 'showall',");
 document.write("'wmode', 'transparent',");
 document.write("'devicefont', 'false',");
 document.write("'id', '"+filename+"',");
 document.write("'bgcolor', 'transparent',");
 document.write("'name', '"+filename+"',");
 document.write("'menu', 'true',");
 document.write("'allowFullScreen', 'false',");
 document.write("'allowScriptAccess','sameDomain',");
 document.write("'movie', 'flash/"+filename+"',");
 document.write("'flashvars', '"+paramstr+"',");
 document.write("'salign', ''");
 document.write(");");
 document.write("</script>");
 

 
}

function show_video_file(videofile,previewfile,sizex,sizey,autoplay,fullscr)
{
 auto_play = false;
 full_screen = false;
 if (autoplay != null){
 auto_play = true;
 }
 if (fullscr != null){
 full_screen = true;
 }
 var vars = {
 width:sizex,
 height:sizey,
 file:videofile,
 image:previewfile,
 fullscreen:full_screen,
 javascriptid:'video',
 enablejs:'true',
 backcolor:'73BF43',
 frontcolor:'FFFFFF',
 lightcolor:'FFFFFF',
 screencolor:'000000',
 autostart:auto_play,
 controlbar:'over'
 };
 
 var params = {
 allowscriptaccess:'always',
 allowfullscreen:full_screen,
 wmode:'transparent'
 };
 
 swfobject.embedSWF("flash/player.swf", "video", sizex, sizey, "9.0.0",'', vars, params);
}


function changeHTML(objectid,newtext){
 document.getElementById(objectid).innerHTML = newtext;
}

/*
* PROTOTYPES for IE and other older browsers
*/
// in array function
function inArray(needle, haystack) {
 for (h in haystack) {
 if (haystack[h] == needle) {
 return true;
 }
 }
 return false;
}
// indexOf function
if (!Array.prototype.indexOf) {
 Array.prototype.indexOf = function(elt /*, from*/) {
 var len = this.length;
 var from = Number(arguments[1]) || 0;
 from = (from < 0)
 ? Math.ceil(from)
 : Math.floor(from);
 if (from < 0)
 from += len;

 for (; from < len; from++) {
 if (from in this && this[from] === elt)
 return from;
 }
 return -1;
 };
} 

/* toggle font / line size */
/* set cookie */
//function setCookie(name, value, expires, path, domain, secure) {
function setCookie(name, value, days) {
 if (days) {
 var date = new Date();
 date.setTime(date.getTime()+(days*24*60*60*1000));
 var expires = "; expires="+date.toGMTString();
 }
 else {
 var expires = "";
 }
 document.cookie = name+"="+value+expires+"; path=/";
}

/* get cookie */
function getCookie(name) {
 var dc = document.cookie;
 var prefix = name + "=";
 var begin = dc.indexOf("; " + prefix);
 if (begin == -1) {
 begin = dc.indexOf(prefix);
 if (begin != 0) return null;
 } else {
 begin += 2;
 }
 var end = document.cookie.indexOf(";", begin);
 if (end == -1) {
 end = dc.length;
 }
 return unescape(dc.substring(begin + prefix.length, end));
}

/* delete cookie */
function deleteCookie( name, path, domain ) {
 if ( getCookie(name) ) 
 document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

var text_sizes = [12, 14, 16];
var line_heights = [1.4, 1.6, 1.8];

var def_text_size = 0;
var def_line_height = 0;

var current_lh = false;
var current_ts = false;

var first_page = false;

var content_placeholder = 'middleblock';

function change_line_height() {

 if (!current_lh)
 current_lh = getCookie('line_height');

 if (!current_lh) current_lh = def_line_height;
 current_lh ++;
 if (current_lh == line_heights.length) current_lh = 0;

 setCookie('line_height', current_lh, 365);
 if (first_page) {
 document.getElementById('push_news').style.lineHeight = line_heights[current_lh] + "em";
 document.getElementById('push_strokovnjak').style.lineHeight = line_heights[current_lh] + "em";
 } else {
 document.getElementById('middleblock').style.lineHeight = line_heights[current_lh] + "em";
 }
}

function change_text_size() {
 if (!current_ts)
 current_ts = getCookie('text_size');
 if (!current_ts) current_ts = def_text_size;
 current_ts ++;
 if (current_ts == text_sizes.length) current_ts = 0;
 setCookie('text_size', current_ts, 365);
 if (first_page) {
 document.getElementById('push_news').style.fontSize = text_sizes[current_ts] + "px";
 document.getElementById('push_strokovnjak').style.fontSize = text_sizes[current_ts] + "px";
 } else {
 document.getElementById('middleblock').style.fontSize = text_sizes[current_ts] + "px";
 }
}

/* returns the x,y coordinates of the current screen (for multi monitor setup) */
function get_top_left(width, height){
 if (parseInt(navigator.appVersion)>3) {
 if (navigator.appName=="Netscape") {
 winW = window.innerWidth;
 winH = window.innerHeight;
 winL = window.screenX;
 winT = window.screenY;
 } else {
 winW = document.body.offsetWidth;
 winH = document.body.offsetHeight;
 winL = window.screenLeft;
 winT = window.screenTop;
 }
 }
 
 var scroll = 0;
 var l = winL + winW/2 - width/2;
 var t = winT + winH/2 - height/2;
 
 
 if(screen.width <= width){
 width=screen.width;
 }
 if(screen.height <= height){
 height=screen.height;
 var t = 0;
 var scroll = 1;
 }
 return Array(t,l);
}


/* generic window opener */
function openwin(uri,title,w,h,scroll,tracking){
 
 if (tracking == undefined) tracking = false;
 
 if (tracking) {
 pageTracker._trackEvent('heaeder', 'Click', 'Radio popup');
 }
 
 if(w){wwidth = w;}else{ wwidth = 380;}
 if(h){wheight = h; }else{ wheight = 380;}
 xy = get_top_left(wwidth, wheight);
 wleft = xy[1];
 wtop = xy[0];
 wnd = window.open(uri, title, "width="+wwidth+", height="+wheight+", left="+wleft+", top="+wtop+", toolbar=no, location=no, scrollbars="+scroll+", status=no, menubar=no, resizable=no, directories=no");
}


function set_background(item_id, bg_class) {
 
 $("#bg_"+item_id).toggleClass(bg_class);
}


function toggle_visibility() {
 if ($("#oblak").css("display") == "none"){
 $("#oblak").css("display","block");
 } else {
 $("#oblak").css("display","none");
 }
}

function next_item() {
 
 var next;
 var current = 0;
 var items_count = $("#tutorial .item").length;
 
 for (var i = 0; i<items_count; i++){
 if ($("#item_"+i).css("display") == "block") {
 current = i;
 $("#item_"+i).css("display","none");
 next = i + 1;
 }
 }
 current = next;
 $("#item_"+next).css("display","block");
 
 if (next == items_count-1) {
 $("#tutorial-forward-button").css("display","none");
 $("#tutorial-goto-playz").css("display","block");
 $("#tutorial-more-about").css("display","block");
 } 
 if (current > 0) {
 $("#tutorial-back-button").css("display","block");
 }
 
}

function previous_item() {
 
 var previous;
 var current;
 var items_count = $("#tutorial .item").length;
 
 for (var i = 0; i<items_count; i++){
 if ($("#item_"+i).css("display") == "block") {
 current = i;
 $("#item_"+i).css("display","none");
 previous = i - 1;
 }
 }
 $("#item_"+previous).css("display","block");
 current = previous;
 if (previous == 0) {
 $("#tutorial-back-button").css("display","none");
 } 
 if (current < items_count) {
 $("#tutorial-forward-button").css("display","block");
 $("#tutorial-goto-playz").css("display","none");
 $("#tutorial-more-about").css("display","none");
 }
 
 
}

function show_gallery_item (galID,itemID) {
 $(galID+" span").css("display","none");
 $(".izbirnik .item a").removeClass("active");
 $("#bimg_"+itemID).css("display","block");
 $("#th_"+itemID).addClass("active");
 return false;
}

/*
 * 
 * telephone slider na ponudbi -> vstopna stran
 */

function init_telephone_showcase(paket) {
 
 if ($('#orto-telefoni').length > 0) {
 
 if (paket == '' || paket == undefined) paket = 0;
 
 $.ajax({
 url: 'ajax.request.php?action=orto_telefoni',
 type:'POST',
 dataType:'html',
 data: {ID: paket},
 success: function(rsp) {
 $('#ajax_telefoni').html(rsp);
 set_telephone_slider();
 }
 });
 
 
 }
 
}

function set_telephone_slider() {
 if ($('#orto-telefoni')) {
 
 var sliding_width = 220;
 var num_elements = $(".telefon-box").length;
 var holder_width = num_elements * 220;
 var holder_position = 0;
 
 $(".holder").css( 'width', holder_width);
 
 if (holder_position == 0) $("#back-button").css("display","none");
 if (num_elements < 2) {
 $("#forward-button").css("display","none");
 } else {
 $("#forward-button").css("display","block");
 }
 
 $("#forward-button").click(function(){
 
 holder_position = holder_position - sliding_width;
 $(".holder").animate({left: holder_position+'-'+sliding_width+'px'},'slow');
 
 if (holder_position < 0) $("#back-button").css("display","block");
 if (holder_position == -holder_width + sliding_width) $(this).css("display","none");
 
 return false;
 });
 
 $("#back-button").click(function(){
 
 holder_position = holder_position + sliding_width;
 $(".holder").animate({left: holder_position+'+'+sliding_width+'px'},'slow');
 
 if (holder_position == 0) $(this).css("display","none");
 if (holder_position > -holder_width + sliding_width) $("#forward-button").css("display","block");
 
 return false;
 });
 }
}


function set_benefiti_slider () {
 if ($("#muziq-benefiti-selector")) {
 
 var container_width = 500;
 var item_width = 125;
 var num_items = $("#benefiti-slider .item").length;
 var slider_width = num_items * item_width;
 var end_position = container_width - slider_width;
 var slider_position = 0;
 
 $("#benefiti-slider").css('width',slider_width);
 $("#btn-left, #btn-right").click(function() { return false; });
 
 $("#btn-left").mousedown(function(){
 $("#benefiti-slider").animate({left: 0}, 'slow');
 });
 
 $("#btn-right").mousedown(function(){
 $("#benefiti-slider").animate({left: end_position}, 'slow');
 });
 
 $("#btn-left, #btn-right").mouseup(function(){ $("#benefiti-slider").stop(); });
 
 } 
}

function set_benefit_content(itemID) {
 
 $("#benefiti-slider .selected").removeClass("selected");
 $("#b"+itemID).addClass("selected");
 
 
 $.ajax({
 url: 'ajax.request.php?action=benefiti',
 type:'POST',
 dataType:'json',
 data: {ID: itemID},
 success: function(rsp) {
 $('#muziq-benefiti').html(rsp.html);
 
 var vars = rsp.flash_vars;
 
 var params = {
 allowscriptaccess:'always',
 allowfullscreen: false,
 wmode: 'transparent'
 };
 
 swfobject.embedSWF(rsp.muziq_tv_swf, "z_muziq_tv_container", "480", "320", "9.0.0", params, vars);
 }
 });
 
 
 //$('#muziq-benefiti').load('ajax.request.php?action=benefiti&ID='+itemID)
 
 //$('#muziq-benefiti').html(zan_geturl('ajax.request.php?action=benefiti&ID='+itemID));
}

function zan_geturl(addr) {
 var r = $.ajax({
 type: 'GET',
 url: addr,
 async: false
 }).responseText;
 return r;
}




function set_muziqnews_slider() {
 if ($("#current-news")) {

 var sliding_width = 597;
 var num_elements = $("#current-news .item").length;
 var slider_width = num_elements * 597;
 var slider_position = 0;
 
 $("#current-news .slider").css( 'width', slider_width);
 if (slider_position == 0) $("#muziq-news-back").css("display","none");
 
 $("#muziq-news-forward").click(function(){
 slider_position = slider_position - sliding_width;
 $("#current-news .slider").animate({ left: slider_position+'-'+sliding_width+'px'}, 'slow');
 if (slider_position < 0) $("#muziq-news-back").css("display","block");
 if (slider_position == -slider_width + sliding_width) $(this).css("display","none");
 return false;
 });
 
 $("#muziq-news-back").click(function(){
 slider_position = slider_position + sliding_width;
 $("#current-news .slider").animate({ left: slider_position+'+'+sliding_width+'px'}, 'slow');
 if (slider_position == 0) $(this).css("display","none");
 if (slider_position > -slider_width + sliding_width) $("#muziq-news-forward").css("display","block"); 
 return false;
 });
 }
}


/*
 * 
 * ORTO feed 
 */

function set_ortofeed_slider() {
 if ($('#ortofeed')) {
 
 var conteiner_height = $("#ortofeed .conteiner").height();
 var slider_height = $("#orto-feed-slider").height();
 var end_pos = conteiner_height - slider_height;
 
 $("#down-button, #up-button").click(function(){ return false; });
 
 $("#up-button").mousedown(function(){
 $("#orto-feed-slider").animate({top: 0}, 'slow');
 });
 
 $("#down-button").mousedown(function(){
 $("#orto-feed-slider").animate({top: end_pos}, 'slow');
 });
 
 $("#down-button, #up-button").mouseup(function(){
 $("#orto-feed-slider").stop();
 });
 }
}


/*function set_topplayz_slider () {
 if ($("#top-playz-holder").length > 0) {
 
 var conteiner_width = $("#top-playz-holder").width();
 var slider_width = $("#top-playz-slider").width();
 var end_pos = conteiner_width - slider_width;
 
 $("#top-playz-left, #top-playz-right").click(function(){ return false; });
 
 $("#top-playz-left").mousedown(function(){
 $("#top-playz-slider").animate({left: 0}, 'slow');
 });
 
 $("#top-playz-right").mousedown(function(){
 $("#top-playz-slider").animate({left: end_pos}, 'slow');
 });
 
 $("#top-playz-left, #top-playz-right").mouseup(function(){
 $("#top-playz-slider").stop();
 });
 
 }
}*/

function set_topplayz_slider () {
 // config
 var mover_offset = 2;
 var mover_interval = 100;
 
 if ($("#top-playz-holder").length > 0) {
 var container_width = $("#top-playz-holder").width();
 
 var slider_width = $("#top-playz-slider").width();
 var end_pos = container_width - slider_width; 
 
 var mover_stoped = false;
 
 if (slider_width>container_width) {
 var container1 = $("#top-playz-slider")[0];
 var container2 = container1.cloneNode(true);
 
 $(container2).css('left', $(container1).width());
 container1.parentNode.appendChild(container2);
 
 container1 = $(container1).css('left', 0);
 container2 = $(container2);
 
 var mover = function() {
 //$('#tweet').html(Math.random());
 
 container1.css('left', parseInt(container1.css('left'))-mover_offset);
 container2.css('left', parseInt(container2.css('left'))-mover_offset);
 
 if (parseInt(container2.css('left'))<0) {
 container1.css('left', slider_width+parseInt(container2.css('left')));
 var tmp = container1;
 container1 = container2;
 container2 = tmp;
 }
 }
 
 var moverInst = setInterval(mover, mover_interval);
 
 var cancelMover = function() {
 mover_stoped = true;
 if (container2) {
 var c = container2[0];
 var p = c.parentNode;
 p.removeChild(c);
 clearInterval(moverInst);
 container2 = null;
 }
 };
 
 var pauseMover = function() {
 clearInterval(moverInst);
 }
 
 $('#top-playz-holder').hover(pauseMover, function() {
 if (!mover_stoped) {
 moverInst = setInterval(mover, mover_interval);
 }
 });
 } else {
 var cancelMover = function() {};
 }
 
 $("#top-playz-left, #top-playz-right").click(function(){ return false; });
 
 $("#top-playz-left").mousedown(function(){
 cancelMover();
 $("#top-playz-slider").animate({left: 0}, 'slow');
 });
 
 $("#top-playz-right").mousedown(function(){
 cancelMover();
 $("#top-playz-slider").animate({left: end_pos}, 'slow');
 });
 
 $("#top-playz-left, #top-playz-right").mouseup(function(){
 $("#top-playz-slider").stop();
 });
 
 }
}


function set_friend_on_playz_slider () {
 
 if ($("#friends-on-playz-holder").length > 0) {
 
 
 var conteiner_width = $("#friends-on-playz-holder").width();
 var slider_width = $("#friends-on-playz-slider").width();
 var end_pos = conteiner_width - slider_width;
 
 
 $("#friends-on-playz-left, #friends-on-playz-right").click(function(){ return false; });
 
 $("#friends-on-playz-left").mousedown(function(){
 $("#friends-on-playz-slider").animate({left: 0}, 'slow');
 });
 
 $("#friends-on-playz-right").mousedown(function(){
 $("#friends-on-playz-slider").animate({left: end_pos}, 'slow');
 });
 
 $("#friends-on-playz-left, #friends-on-playz-right").mouseup(function(){
 $("#friends-on-playz-slider").stop();
 });
 
 }
 
}



function parse_message_playz(message) {
 var return_array = {};

 var patterns = {
 'location' : /#([^$\* ]*)/,
 'music' : /\$([^#\*]*)/,
 'status' : /\*([^#\$]*)/
 };
 
 var pattern;
 var matches;
 for (var key in patterns) {
 pattern = patterns[key];

 matches = message.match(pattern);
 if (matches && matches[1]) {
 return_array[key] = matches[1];
 }
 }
 return return_array;
}




function get_authorised_dealers(id) {
 
 $.ajax({
 url:'ajax.request.php?action=pooblasceni_prodajalci',
 type:'POST',
 dataType:'html',
 data: {ID: id},
 success: function(rsp) {
 $('#list-prodajna-mesta').html(rsp);
 }
 });
 
}




/* form uploadfile field formation
 * 
 * */

var W3CDOM = (document.createElement && document.getElementsByTagName);

$.fn.renderFileUpload = function() {
 if ($('div.fakefile').size()==0) {
 var fakeFileUpload = document.createElement('div');
 fakeFileUpload.className = 'fakefile';
 fakeFileUpload.appendChild(document.createElement('input'));
 var button = document.createElement('span');
 button.className = 'button';
 fakeFileUpload.appendChild(button);
 } else {
 fakeFileUpload = $('div.fakefile').get(0);
 }

 return this.each(function() {
 if (!W3CDOM) return;
 
 $(this).addClass('hidden_file');
 
 var clone = fakeFileUpload.cloneNode(true);
 
 this.parentNode.appendChild(clone);
 this.relatedElement = clone.getElementsByTagName('input')[0];
 this.btn = clone.getElementsByTagName('span')[0];
 this.onchange = this.onmouseout = function () {
 this.relatedElement.value = this.value;
 }
 this.onmouseover = function() {
 this.btn.style.backgroundPosition = 'bottom left';
 }
 this.onmouseout = function() {
 this.btn.style.backgroundPosition = 'top left';
 }
 });
}

$.fn.centerScreen = function(loaded) {
 return this.each(function() {
 var obj = $(this);
 if(!loaded) {
 obj.css('top', $(window).scrollTop()+$(window).height()/2-obj.height()/2);
 obj.css('left', $(window).scrollLeft()+$(window).width()/2-obj.width()/2);
 $(window).resize(function() {
 obj.centerScreen(!loaded);
 });
 $(document).scroll(function() {
 obj.centerScreen(!loaded);
 });
 $(window).scroll(function() {
 obj.centerScreen(!loaded);
 });
 } else {
 obj.stop();
 obj.animate({
 top: $(window).scrollTop()+$(window).height()/2-obj.height()/2,
 left: $(window).scrollLeft()+$(window).width()/2-obj.width()/2
 }, 200, 'linear');
 }
 });
}


$(document).ready(function() {
 set_ortofeed_slider();
 //set_telephone_slider();
 set_topplayz_slider();
 set_muziqnews_slider();
 set_friend_on_playz_slider();
 $('input[type=file]').renderFileUpload();
});

/*
* STAR RATING
*/
$(function() {
 $('ul.star-rating-votable li a').click(function() { 
 if ($(this).parent().hasClass('current-rating')) {
 return false;
 }
 
 var container = $($(this).parents('ul.star-rating-votable')[0]);
 var rate = parseInt(this.rel.replace(/^Rate/, ''));
 
 $('li', container).hide();
 $('li.current-rating', container).css('width', parseInt(100*rate/5)+'%').show();
 
 var match = $('li.current-rating a', container).attr('rel').match(/^(.*)\|(.*)$/);
 var data = {
 type: match[1],
 id: match[2],
 rate:this.rel
 };
 
 $.ajax({
 url:'ajax.request.php?action=star_rate',
 type:'POST',
 dataType:'json',
 data: data,
 success: function(rsp) {
 if (rsp.success) {
 $('li.current-rating', container).css('width', parseInt(100*rsp.star_rate/5)+'%');
 } else {
 $('li', container).show();
 $('li.current-rating', container).hide();
 }
 },
 error:function() {
 $('li', container).show();
 $('li.current-rating', container).hide();
 }
 });
 
 return false;
 
 });

 $('ul.ortotrip-rating-votable li a').click(function() {
 // submission function
 var submit = function(data, container) {
 var data = $('#ortotrip_castvote_dlg').data('data');

 $.ajax({
 url:'ajax.request.php?action=ortotrip_rate',
 type:'POST',
 dataType:'json',
 data: data,
 success: function(rsp) {
 var container = $('#ortotrip_castvote_dlg').data('container');
 if (rsp.success) {
 var userRate = parseInt(rsp.star_rate.replace('Rate', ''));
 $('li.current-rating', container).css('width', parseInt(100*userRate/5)+'%');

 if (typeof(params.currentVoteSelector.closest)!='undefined' && params.currentVoteSelector.closest) {
 var closest = $(container).closest(params.currentVoteSelector.closest);
 } else {
 var closest = $(container);
 }
 var currRateEl = $(params.currentVoteSelector.childs, closest);

 if (typeof(params.currentVoteSelector.topLevel)!='undefined' && params.currentVoteSelector.topLevel) {
 currRateEl = currRateEl.add(params.currentVoteSelector.topLevel, document.body);
 }

 currRateEl.each(function() {
 var score = parseInt($(this).html());
 score += userRate;
 $(this).html(score);
 });

 $('#ortotrip_castvote_dlg').data('has_voted', true);
 
 if (rsp.has_signed_up) {
 $('#ortotrip_castvote_dlg').data('participating', true);

 $('#ortotrip_castvote_dlg .inner .top, #ortotrip_castvote_dlg .inner .bottom, #ortotrip_castvote_dlg .inner .saving').hide();
 $('#ortotrip_castvote_dlg .inner').prepend('<div class="thanks">Hvala za oddan glas. Uvrstili smo te v nagradno žrebanje.</div>');
 setTimeout(function() {
 $('#ortotrip_castvote_dlg').fadeOut();
 }, 2000);
 } else {
 $('#ortotrip_castvote_dlg').fadeOut();
 }
 } else {
 alert('Zgodila se je napaka pri glasovanju. Poiskusite kasneje!');
 $('li', container).show();
 $('li.current-rating', container).hide();
 $('#ortotrip_castvote_dlg').fadeOut();
 }
 },
 error:function() {
 alert('Zgodila se je napaka pri glasovanju. Poiskusite kasneje!');
 $('li', container).show();
 $('li.current-rating', container).hide();
 $('#ortotrip_castvote_dlg').fadeOut();
 }
 });
 }

 var createForm = function() {
 // create form if form does not exist
 if ($('#ortotrip_castvote_dlg').size()==0) {
 $(document.body).append(
 '<div id="ortotrip_castvote_dlg" style="display:none" class="pngfix">'+
 '<div class="inner">'+
 '<div class="saving">Ocena se shranjuje ...</div>'+
 '<div class="top">'+
 '<label>Želim samo oddati točke za prispevek.</label>'+
 '<button name="justvote"></button>'+
 '</div>'+

 '<div class="bottom">'+
 '<span>Želim glasovati in <strong>sodelovati v nagradnem žrebanju</strong> za telefon NOKIA N97 mini. </span>'+
 '<button></button>'+
 '<label>Vpiši svoj email naslov:</label>'+
 '<input type="text" name="ortotrip_castvote_email" />'+
 '</div>'+
 '<a class="close" href="#">zapri</a>'+
 '</div>'+
 '</div>'
 );
 $('#ortotrip_castvote_dlg input[name=ortotrip_castvote_email]').focus(function() {
 $('#ortotrip_castvote_dlg input[value=castandparticipate]').attr('checked', 'checked');
 });
 $('#ortotrip_castvote_dlg input[value=castandparticipate]').click(function() {
 $('#ortotrip_castvote_dlg input[name=ortotrip_castvote_email]').focus();
 });
 $('#ortotrip_castvote_dlg button').click(function() {
 var email = '';

 if (this.name!='justvote') {
 if (!$('#ortotrip_castvote_dlg input[name=ortotrip_castvote_email]').val()) {
 alert('Vnos e-mail naslova je obvezen za udeležbo v nagradni igri!');
 return false;
 }
 email = $('#ortotrip_castvote_dlg input[name=ortotrip_castvote_email]').val();
 }
 //$('#ortotrip_castvote_dlg').
 var data = $('#ortotrip_castvote_dlg').data('data') ;
 data.email = email;
 $('#ortotrip_castvote_dlg .inner .top, #ortotrip_castvote_dlg .inner .bottom').hide();
 $('#ortotrip_castvote_dlg').data('data', data);
 $('#ortotrip_castvote_dlg .inner .saving').show();
 submit();
 });
 $('#ortotrip_castvote_dlg a.close').click(function() {
 var container = $('#ortotrip_castvote_dlg').data('container');

 if (!$('#ortotrip_castvote_dlg').data('has_voted')) {
 $('li', container).show();
 $('li.current-rating', container).hide();
 }

 $('#ortotrip_castvote_dlg').fadeOut();
 return false;
 });
 }
 }

 var showForm = function() {
 var data = $('#ortotrip_castvote_dlg').data('data');
 var container = $('#ortotrip_castvote_dlg').data('container');

 $('#ortotrip_castvote_dlg .inner .top, #ortotrip_castvote_dlg .inner .bottom').show();
 $('#ortotrip_castvote_dlg .inner .saving').hide();
 $('#ortotrip_castvote_dlg input[name=ortotrip_castvote_email]').val(params.email);
 $('#ortotrip_castvote_dlg input[value=castandparticipate]').attr('checked', 'checked');

 var position = $(boxContainer).offset();
 position.left -= 20;
 position.top -= 162;
 $('#ortotrip_castvote_dlg').css(position).fadeIn();
 if (typeof(DD_belatedPNG)!='undefined') {
 DD_belatedPNG.fix('.pngfix');
 }
 }

 if ($(this).parent().hasClass('current-rating')) {
 return false;
 }

 // preparing params
 var container = $(this).parents('ul.ortotrip-rating-votable:first');
 var boxContainer = $(container).parents('.ortotrip-rating:first');
 var rate = parseInt(this.rel.replace(/^Rate/, ''));

 /*
 * 0 ... post id
 * 1 ... default email (only for logged users)
 * 2 ... is already participating
 */
 var params = eval('('+$('li.current-rating a', container).attr('rel')+')');
 var data = {
 id: params.id,
 rate: this.rel
 };

 // fix stars
 $('li', container).hide();
 $('li.current-rating', container).css('width', parseInt(100*rate/5)+'%').show();

 createForm();
 $('#ortotrip_castvote_dlg').data('data', data);
 $('#ortotrip_castvote_dlg').data('container', container);

 $('#ortotrip_castvote_dlg').data('has_voted', false);
 if (!parseInt(params.participator) && !$('#ortotrip_castvote_dlg').data('participating')) {
 showForm();
 } else {
 submit();
 }
 
 return false;

 });

});

/*
* Playz location selector
*/
var playz_location_myplayz_events = function(cont) {
 cont = $(cont);
 
 var reload = function() {
 var data = {};
 try {
 data = eval('('+$('input.playz_location_other_params', cont).val()+')');
 } catch (e) {
 data = {};
 };
 
 if (typeof(data.length)!='undefined') data = {};
 
 data.id = cont.attr('id');
 data.type = 'my-playzes';
 data.page = $('.myplayz .pageselector span.selected a').attr('rel');
 data.filter_text = $('.myplayz .filter_text', cont).val();
 
 var height = $('.myplayz', cont).height();
 $('.myplayz', cont).css('height', height);
 $('.myplayz', cont).html('Nalagam podatke ...');
 
 $.ajax({
 url:'ajax.request.php?action=playz-location-selector',
 type:'post',
 cache:false,
 data: data,
 dataType: 'json',
 success:function(rsp) {
 $('.myplayz', cont).html(rsp.html);
 $('.myplayz', cont).css('height', 'auto');

 var id;
 id = $('.current_myplayz', cont).val();
 if (id) {
 var li = $('.myplayz .items li a[rel="'+id+'"]').parents('li');
 if (li.size()>0) {
 $(li[0]).addClass('selected');
 }
 }

 playz_location_myplayz_events(cont);
 }
 });
 
 return false;
 }
 
 $('.myplayz .pageselector a', cont).click(function() {
 $('.myplayz .pageselector span', cont).removeClass('selected');
 $($(this).parents('span')[0]).addClass('selected');
 reload();
 return false;
 });
 $('.myplayz .items li a', cont).click(function() {
 var event = jQuery.Event('myplayzChange');
 $('.current_myplayz', cont).val(this.rel);
 event.id = parseInt(this.rel);
 event.code = $('.code', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.name = $('.name', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.address = $('.address', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.playz_id = $('.playz_id', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 $('.myplayz .items li', cont).removeClass('selected');
 $($(this).parents('li')[0]).addClass('selected');
 cont.trigger(event);
 return false;
 });
 
 $('.myplayz .filter_text').keydown(function(e) {
 if (e.keyCode==13) {
 reload();
 return false;
 } 
 
 });
 
 $('.myplayz .filter_enforce').click(reload);
}

var playz_location_lastvisited_events = function(cont) {
 cont = $(cont);
 
 var reload = function() {
 var data = {};
 try {
 data = eval('('+$('input.playz_location_other_params', cont).val()+')');
 } catch (e) {
 data = {};
 };
 
 if (typeof(data.length)!='undefined') data = {};
 
 data.id = cont.attr('id');
 data.type = 'last-visited';
 data.page = $('.lastvisited .pageselector span.selected a').attr('rel');
 data.filter_text = $('.lastvisited .filter_text', cont).val();
 
 var height = $('.lastvisited', cont).height();
 $('.lastvisited', cont).css('height', height);
 $('.lastvisited', cont).html('Nalagam podatke ...');
 
 $.ajax({
 url:'ajax.request.php?action=playz-location-selector',
 type:'post',
 cache:false,
 data: data,
 dataType: 'json',
 success:function(rsp) {
 $('.lastvisited', cont).html(rsp.html);
 $('.lastvisited', cont).css('height', 'auto');

 var id;
 id = $('.current_lastvisited', cont).val();
 if (id) {
 var li = $('.lastvisited .items li a[rel="'+id+'"]').parents('li');
 if (li.size()>0) {
 $(li[0]).addClass('selected');
 }
 }

 playz_location_lastvisited_events(cont);
 }
 });

 return false;
 }
 
 $('.lastvisited .pageselector a', cont).click(function() {
 $('.lastvisited .pageselector span', cont).removeClass('selected');
 $($(this).parents('span')[0]).addClass('selected');
 reload();
 return false;
 });
 $('.lastvisited .items li a', cont).click(function() {
 var event = jQuery.Event('lastvisitedChange');
 $('.current_lastvisited', cont).val(this.rel);
 event.id = parseInt(this.rel);
 event.code = $('.code', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.name = $('.name', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.address = $('.address', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.playz_id = $('.playz_id', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 $('.lastvisited .items li', cont).removeClass('selected');
 $($(this).parents('li')[0]).addClass('selected');
 cont.trigger(event);
 return false;
 });
 
 $('.lastvisited .filter_text').keydown(function(e) {
 if (e.keyCode==13) {
 reload();
 return false;
 } 
 
 });
 
 $('.lastvisited .filter_enforce').click(reload);

}

var playz_location_allplayz_events = function(cont) {
 cont = $(cont);
 
 var reload = function() {
 var data = {};
 try {
 data = eval('('+$('input.playz_location_other_params', cont).val()+')');
 } catch (e) {
 data = {};
 };
 
 if (typeof(data.length)!='undefined') data = {};
 
 data.id = cont.attr('id');
 data.type = 'all-playzes';
 data.page = $('.allplayz .pageselector span.selected a').attr('rel');
 data.filter_text = $('.allplayz .filter_text', cont).val();
 
 var height = $('.allplayz', cont).height();
 $('.allplayz', cont).css('height', height);
 $('.allplayz', cont).html('Nalagam podatke ...');
 
 $.ajax({
 url:'ajax.request.php?action=playz-location-selector',
 type:'POST',
 cache:false,
 data: data,
 dataType: 'json',
 success:function(rsp) {
 $('.allplayz', cont).html(rsp.html);
 $('.allplayz', cont).css('height', 'auto');

 var id;
 id = $('.current_allplayz', cont).val();
 if (id) {
 var li = $('.allplayz .items li a[rel="'+id+'"]').parents('li');
 if (li.size()>0) {
 $(li[0]).addClass('selected');
 }
 }

 playz_location_allplayz_events(cont);
 }
 });

 return false;
 };
 
 $('.allplayz .pageselector a', cont).click(function() {
 $('.allplayz .pageselector span', cont).removeClass('selected');
 $($(this).parents('span')[0]).addClass('selected');
 reload();
 return false;
 });
 $('.allplayz .items li a', cont).click(function() {
 var event = jQuery.Event('allplayzChange');
 $('.current_allplayz', cont).val(this.rel);
 event.id = parseInt(this.rel);
 event.code = $('.code', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.name = $('.name', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.address = $('.address', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 event.playz_id = $('.playz_id', $(this).parent()).html().replace(/(^\s+)|(\s+$)/g, '');
 $('.allplayz .items li', cont).removeClass('selected');
 $($(this).parents('li')[0]).addClass('selected');
 cont.trigger(event);
 return false;
 });
 
 $('.allplayz .filter_text').keydown(function(e) {
 if (e.keyCode==13) {
 reload();
 return false;
 } 
 
 });
 
 $('.allplayz .filter_enforce').click(reload);
 
}

function init_playz_location_selector(rel) {
 if (typeof(rel)=='undefined') {
 rel = null;
 }
 
 $('.playz_location_selector', rel).each(function() {
 var cont = this;

 playz_location_myplayz_events(this);
 playz_location_lastvisited_events(this);
 playz_location_allplayz_events(this);

 $('.playz_location_selector_tabs a', this).click(function() {
 $('.playz_location_selector_tabs li', cont).removeClass('selected');
 $($(this).parents('li')[0]).addClass('selected');
 $('.playz_location_selector_tab', cont).hide();
 $('.playz_location_selector_tab.'+this.rel, cont).show();
 $('.current_type', cont).val(this.rel);
 return false;
 });
 });
}

$(function() {
 init_playz_location_selector();
 
});

 
var DelayedTask = function(callback, delayTime, scopeObj) {
 var timer = null;
 var delay = delayTime;
 var cb = callback;
 var scope = scopeObj;
 var dt = {
 start: function() {
 if (timer) {
 clearTimeout(timer);
 timer = null;
 }
 timer = setTimeout(function() {
 cb.call(scope, dt);
 }, delay);
 },
 getCallback: function() {
 return cb;
 }
 }
 return dt;
};

$(function() {
 var friend_search_fun = new DelayedTask(function(dt) {
 var text = $('input', $(this).parents('.friend-search')[0]).val().toLowerCase();
 text = text.replace(/^\s+|\s+$/, '');
 
 var show_users = function(rsp) {
 dt.ajaxRequestRunning = false;
 $('#user-friends .Scroller-Container .search-status').remove();
 $('#user-friends .Scroller-Container .user').remove();
 $('#user-friends .Scroller-Container .other-users').remove();
 $('#user-friends .Scroller-Container').append('<div class="other-users">Ostali uporabniki</div>');
 
 if (rsp.success) {
 var fc = $('#user-friends .Scroller-Container');
 
 for (var i=0; i<rsp.users.length; i++) {
 var user = rsp.users[i];
 fc.append(
 '<div class="friend user">'+
 '<span class="avatar"><a href="'+user.url+'"><img src="'+user.avatar+'"/></a></span>'+
 '<span class="nickname"><a href="'+user.url+'">'+user.nick+'</a></span>'+
 '</div>'); 
 }
 
 if (rsp.moreResults) {
 $('#user-friends .Scroller-Container').append('<div class="search-status">Prikazujejo se zgolj prvih 10 zadetkov. <a href="'+rsp.moreResultsUrl+'">Preglej vse</a></div>');
 }
 }
 fix_scroller();
 };
 
 var fix_scroller = function() {
 scroller = new jsScroller(document.getElementById("Container"), scroller_width, scroller_height);
 scrollbar = new jsScrollbar (document.getElementById("Scrollbar-Container"), scroller, true, scrollbarEvent);
 scrollbar._scrollDist = 10;
 }
 
 if (text!='' && text!='Poišči frende...') {
 if (text==dt.lastSearch) {
 return;
 } else {
 dt.lastSearch = text;
 }
 
 if (dt.ajaxRequestRunning == false) {
 dt.ajaxRequestRunning = true;
 $('#user-friends .Scroller-Container').append('<div class="search-status loading">Iščem prijatelje ...</div>');
 $.ajax({
 url:'ajax.request.php?action=user_search',
 type:'POST',
 dataType:'json',
 data:{
 text:text
 },
 success:show_users,
 error:show_users
 });
 }
 $('#user-friends .friend').each(function() {
 var nickname = $('.nickname a', this).html().toLowerCase();
 if (nickname.indexOf(text)!=-1) {
 $(this).show();
 } else {
 $(this).hide();
 }
 });
 
 fix_scroller();
 } else {
 $('#user-friends .friend').show();
 $('#user-friends .Scroller-Container .user').remove();
 $('#user-friends .Scroller-Container .other-users').remove();
 fix_scroller();
 }
 return false;
 }, 1000, $('.friend-search input'));
 friend_search_fun.lastSearch = '';
 friend_search_fun.ajaxRequestRunning = false;
 $('.friend-search button').click(friend_search_fun.getCallback());
 $('.friend-search input').focus(function() {
 if (this.value=='Poišči frende...') {
 this.value = '';
 }
 }).blur(function() {
 if (this.value=='') {
 this.value='Poišči frende...';
 }
 }).keyup(function() {
 friend_search_fun.start();
 });
});
 
jQuery.fn.textLimiter = function(cf) {
 return this.each(function(){
 var el = $(this);
 
 if (typeof(cf)=='undefined') {
 cf = {};
 }
 
 if (typeof(cf.maxLength)=='undefined') {
 cf.maxLength = 5;
 }
 
 if (typeof(cf.text)=='undefined') {
 cf.text = 'število preostalih znakov: {remaining}';
 }
 
 var setText = function() {
 var data = {
 current: el.val().length,
 remaining: cf.maxLength - el.val().length,
 total: cf.maxLength
 }
 
 var text = cf.text;
 for (var key in data) {
 text = text.replace(new RegExp('{'+key+'}'), data[key]);
 }
 
 $(cf.element).html(text);
 
 if (el.val().length>cf.maxLength) {
 el.val(el.val().substring(0,cf.maxLength));
 }
 }
 setText();
 
 el.keydown(function(e) {
 //Get the event object (for IE) 
 var ob = e || event; 
 //Get the code of key pressed 
 var keyCode = ob.keyCode; 
 //Check if it has a selected text 
 var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd; 
 //return false if can't write more 
 return !(this.value.length >= cf.maxLength && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection); 
 }).keyup(setText);
 
 
 });
};

$(function() {
 if ($('.ad-gallery').size()>0) {
 var galleries = $('.ad-gallery').adGallery();
 }
});
$(document).ready(function(){
 $('.popup-pogoji-href').click(function(){
 var popupUrl = $(this).attr('href');
 //var popupTitle = $('.popup-pogoji-href span').text();
 
 openwin(popupUrl,'',500,600,'yes');
 return false;
 });
 $('.video_player_link').click(function() {
 $(this).modal({width:600, height:440, src:this.href}).open(); 
 return false;
 });
});
//$(document).ready(function(){
// if ($('.popover').size()>0) {
// $(".popover").ceebox({htmlWidth:600,htmlHeight:444});
// }
//});
function open_popover() {
 //$.ceebox.show('', 'popover_video.php', false);
 $(this).modal({width:600, height:440}).open();
}
function open_popover_trip() {
 //$.ceebox.show('', 'popover_video.php', false);
 href = TRIP_FLASH_HREF;
 $(this).modal({width:640, height:352, src:href}).open();
}

function open_popover_stream() {
 //$.ceebox.show('', 'popover_video.php', false);
 href = "/popover_stream.php";
 $(this).modal({width:960, height:720, src:href}).open();
}

function showTelefoni(xml_file) {
 
 var flashvars = {};
 var params = {};
 var attributes = {};
 
 flashvars.xmlpath = xml_file;
 
 params.base= 'flash/';
 params.play = 'true';
 params.loop = 'true';
 
 swfobject.embedSWF('flash/telefoni.swf', 'flash-promo-telefoni', '190', '310', '8', '', flashvars, params, attributes);
}


function swapTelefoni(mode) {
 
 xml_file = 'http://www.orto.si/ajax.request.php?action=first-page-promo-phones'; 
 
 if (mode == 'ortoberi') {
 xml_file = 'http://www.orto.si/ajax.request.php?action=first-page-promo-phones&PackageID=507';
 } else if (mode == 'ortounulo') {
 xml_file = 'http://www.orto.si/ajax.request.php?action=first-page-promo-phones&PackageID=506';
 } else if (mode == 'ortomuziq') {
 xml_file = 'http://www.orto.si/ajax.request.php?action=first-page-promo-phones&PackageID=508';
 } else if (mode == 'all') {
 xml_file = 'http://www.orto.si/ajax.request.php?action=first-page-promo-phones';
 }
 
 showTelefoni(escape(xml_file));
}

$(function() {
 $('#improper_content').change(function() {
 if (this.value) {
 var closeDlg = function(e) {
 if (typeof(e)=='undefined') {
 var trg = false;
 } else {
 var trg = e.originalTarget;
 }

 var ex;
 try {
 var id = trg.id;
 } catch (ex) {
 return false;
 }

 if (trg &&
 ($(trg).attr('id')=='improper_content_dlg' ||
 $(trg).parents('#improper_content_dlg').size()>0)) {

 return false;
 } else {
 var el = $('#improper_content_dlg')[0];
 var p = el.parentNode;
 p.removeChild(el);
 }
 };

 var submitDlg = function() {
 $('button, textarea', dlg).attr('disabled', 'disabled');

 var data = {
 reason_type: $('.reason_type', dlg).html(),
 post_id: $('.post_id', dlg).html(),
 reason: $('textarea', dlg).val()
 }

 $.ajax({
 url:'ajax.request.php?action=improper_content',
 type:'POST',
 dataType:'json',
 data:data,
 success:function(rsp) {
 closeDlg();
 if (!rsp.success) {
 alert(rsp.msg);
 } else {
 $('#improper_content').attr('disabled', 'disabled');
 alert('Hvala za prijavo neprimerne vsebine!');
 }
 }
 });
 };

 var dialog =
 '<div id="improper_content_dlg">'+
 '<span class="reason_type">{type}</span>'+
 '<span class="post_id">{id}</span>'+
 '<div class="reason">Razlog:<br /><strong>{reason}</strong></div>'+
 '<div class="desc">Opis:<br/><textarea></textarea></div>'+
 '<div class="submit"><button class="ok">Prijavi</button><button class="cancel">Prekliči</button></div>'+
 '<div class="wrn">'+
 'Preden prijavite, preverite če zapis res krši <a href="#">pravila in pogoje</a> '+
 'sodelovanja v skupnosti. Napačna ali zlonamerna prijava je pravtako kršitev '+
 '<a href="#">pravil in pogojev</a>.'+
 '</div>'+
 '</div>';
 dialog = dialog
 .replace('{reason}', this.options[this.selectedIndex].innerHTML);

 $(document.body).append(dialog);

 var dlg = $('#improper_content_dlg').hide();
 var anchor = $('#improper_content');
 var offset = anchor.offset();

 $('.reason_type', dlg).html(this.value);
 $('.post_id', dlg).html(location.search.match(/id=([0-9]+)/)[1]);

 $('button.cancel', dlg).click(function() {closeDlg(); });
 $('button.ok', dlg).click(submitDlg);

 this.selectedIndex = 0;
 dlg.css(offset).show();
 setTimeout(function() {
 $(document.body).one('click', closeDlg)
 }, 1);
 }

 });

});


function toggle_table() {
 

 $("#opcije-box").toggleClass("hidden");
 
 if ($("#opcije-box").hasClass("hidden")) { 
 setCookie('info_table','hidden');
 } else {
 setCookie('info_table','opened');
 }
 
}


function jsScroller (o, w, h) {
 var self = this;
 var list = o.getElementsByTagName("div");
 for (var i = 0; i < list.length; i++) {
 if (list[i].className.indexOf("Scroller-Container") > -1) {
 o = list[i];
 }
 }
 
 //Private methods
 this._setPos = function (x, y) {
 if (x < this.viewableWidth - this.totalWidth) 
 x = this.viewableWidth - this.totalWidth;
 if (x > 0) x = 0;
 if (y < this.viewableHeight - this.totalHeight) 
 y = this.viewableHeight - this.totalHeight;
 if (y > 0) y = 0;
 this._x = x;
 this._y = y;
 with (o.style) {
 left = this._x +"px";
 top = this._y +"px";
 }
 };
 
 //Public Methods
 this.reset = function () {
 this.content = o;
 this.totalHeight = o.offsetHeight;
 this.totalWidth = o.offsetWidth;
 this._x = 0;
 this._y = 0;
 with (o.style) {
 left = "0px";
 top = "0px";
 }
 };
 this.scrollBy = function (x, y) {
 this._setPos(this._x + x, this._y + y);
 };
 this.scrollTo = function (x, y) {
 this._setPos(-x, -y);
 };
 this.stopScroll = function () {
 if (this.scrollTimer) window.clearInterval(this.scrollTimer);
 };
 this.startScroll = function (x, y) {
 this.stopScroll();
 this.scrollTimer = window.setInterval(
 function(){ self.scrollBy(x, y); }, 40
 );
 };
 this.swapContent = function (c, w, h) {
 o = c;
 var list = o.getElementsByTagName("div");
 for (var i = 0; i < list.length; i++) {
 if (list[i].className.indexOf("Scroller-Container") > -1) {
 o = list[i];
 }
 }
 if (w) this.viewableWidth = w;
 if (h) this.viewableHeight = h;
 this.reset();
 };
 
 //variables
 this.content = o;
 this.viewableWidth = w;
 this.viewableHeight = h;
 this.totalWidth = o.offsetWidth;
 this.totalHeight = o.offsetHeight;
 this.scrollTimer = null;
 this.reset();
};



function jsScrollbar (o, s, a, ev) {
 var self = this;
 
 this.reset = function () {
 //Arguments that were passed
 this._parent = o;
 this._src = s;
 this.auto = a ? a : false;
 this.eventHandler = ev ? ev : function () {};
 //Component Objects
 this._up = this._findComponent("Scrollbar-Up", this._parent);
 this._down = this._findComponent("Scrollbar-Down", this._parent);
 this._yTrack = this._findComponent("Scrollbar-Track", this._parent);
 this._yHandle = this._findComponent("Scrollbar-Handle", this._yTrack);
 //Height and position properties
 this._trackTop = findOffsetTop(this._yTrack);
 this._trackHeight = this._yTrack.offsetHeight;
 this._handleHeight = this._yHandle.offsetHeight;
 this._x = 0;
 this._y = 0;
 //Misc. variables
 this._scrollDist = 5;
 this._scrollTimer = null;
 this._selectFunc = null;
 this._grabPoint = null;
 this._tempTarget = null;
 this._tempDistX = 0;
 this._tempDistY = 0;
 this._disabled = false;
 this._ratio = (this._src.totalHeight - this._src.viewableHeight)/(this._trackHeight - this._handleHeight);
 
 this._yHandle.ondragstart = function () {return false;};
 this._yHandle.onmousedown = function () {return false;};
 this._addEvent(this._src.content, "mousewheel", this._scrollbarWheel);
 this._removeEvent(this._parent, "mousedown", this._scrollbarClick);
 this._addEvent(this._parent, "mousedown", this._scrollbarClick);
 
 this._src.reset();
 with (this._yHandle.style) {
 top = "0px";
 left = "0px";
 }
 this._moveContent();
 
 if (this._src.totalHeight < this._src.viewableHeight) {
 this._disabled = true;
 this._yHandle.style.visibility = "hidden";
 if (this.auto) this._parent.style.visibility = "hidden";
 } else {
 this._disabled = false;
 this._yHandle.style.visibility = "visible";
 this._parent.style.visibility = "visible";
 }
 };
 this._addEvent = function (o, t, f) {
 if (o.addEventListener) o.addEventListener(t, f, false);
 else if (o.attachEvent) o.attachEvent('on'+ t, f);
 else o['on'+ t] = f;
 };
 this._removeEvent = function (o, t, f) {
 if (o.removeEventListener) o.removeEventListener(t, f, false);
 else if (o.detachEvent) o.detachEvent('on'+ t, f);
 else o['on'+ t] = null;
 };
 this._findComponent = function (c, o) {
 var kids = o.childNodes;
 for (var i = 0; i < kids.length; i++) {
 if (kids[i].className && kids[i].className == c) {
 return kids[i];
 }
 }
 };
 //Thank you, Quirksmode
 function findOffsetTop (o) {
 var t = 0;
 if (o.offsetParent) {
 while (o.offsetParent) {
 t += o.offsetTop;
 o = o.offsetParent;
 }
 }
 return t;
 };
 this._scrollbarClick = function (e) {
 if (self._disabled) return false;
 
 e = e ? e : event;
 if (!e.target) e.target = e.srcElement;
 
 if (e.target.className.indexOf("Scrollbar-Up") > -1) self._scrollUp(e);
 else if (e.target.className.indexOf("Scrollbar-Down") > -1) self._scrollDown(e);
 else if (e.target.className.indexOf("Scrollbar-Track") > -1) self._scrollTrack(e);
 else if (e.target.className.indexOf("Scrollbar-Handle") > -1) self._scrollHandle(e);
 
 self._tempTarget = e.target;
 self._selectFunc = document.onselectstart;
 document.onselectstart = function () {return false;};
 
 self.eventHandler(e.target, "mousedown");
 self._addEvent(document, "mouseup", self._stopScroll, false);
 
 return false;
 };
 this._scrollbarDrag = function (e) {
 e = e ? e : event;
 var t = parseInt(self._yHandle.style.top);
 var v = e.clientY + document.body.scrollTop - self._trackTop;
 with (self._yHandle.style) {
 if (v >= self._trackHeight - self._handleHeight + self._grabPoint)
 top = self._trackHeight - self._handleHeight +"px";
 else if (v <= self._grabPoint) top = "0px";
 else top = v - self._grabPoint +"px";
 self._y = parseInt(top);
 }
 
 self._moveContent();
 };
 this._scrollbarWheel = function (e) {
 e = e ? e : event;
 var dir = 0;
 if (e.wheelDelta >= 120) dir = -1;
 if (e.wheelDelta <= -120) dir = 1;
 
 self.scrollBy(0, dir * 20);
 e.returnValue = false;
 };
 this._startScroll = function (x, y) {
 this._tempDistX = x;
 this._tempDistY = y;
 this._scrollTimer = window.setInterval(function () {
 self.scrollBy(self._tempDistX, self._tempDistY); 
 }, 40);
 };
 this._stopScroll = function () {
 self._removeEvent(document, "mousemove", self._scrollbarDrag, false);
 self._removeEvent(document, "mouseup", self._stopScroll, false);
 
 if (self._selectFunc) document.onselectstart = self._selectFunc;
 else document.onselectstart = function () { return true; };
 
 if (self._scrollTimer) window.clearInterval(self._scrollTimer);
 self.eventHandler (self._tempTarget, "mouseup");
 };
 this._scrollUp = function (e) {this._startScroll(0, -this._scrollDist);};
 this._scrollDown = function (e) {this._startScroll(0, this._scrollDist);};
 this._scrollTrack = function (e) {
 var curY = e.clientY + document.body.scrollTop;
 this._scroll(0, curY - this._trackTop - this._handleHeight/2);
 };
 this._scrollHandle = function (e) {
 var curY = e.clientY + document.body.scrollTop;
 this._grabPoint = curY - findOffsetTop(this._yHandle);
 this._addEvent(document, "mousemove", this._scrollbarDrag, false);
 };
 this._scroll = function (x, y) {
 if (y > this._trackHeight - this._handleHeight) 
 y = this._trackHeight - this._handleHeight;
 if (y < 0) y = 0;
 
 this._yHandle.style.top = y +"px";
 this._y = y;
 
 this._moveContent();
 };
 this._moveContent = function () {
 this._src.scrollTo(0, Math.round(this._y * this._ratio));
 };
 
 this.scrollBy = function (x, y) {
 this._scroll(0, (-this._src._y + y)/this._ratio);
 };
 this.scrollTo = function (x, y) {
 this._scroll(0, y/this._ratio);
 };
 this.swapContent = function (o, w, h) {
 this._removeEvent(this._src.content, "mousewheel", this._scrollbarWheel, false);
 this._src.swapContent(o, w, h);
 this.reset();
 };
 
 this.reset();
};



function scrollbarEvent (o, type) {
 if (type == "mousedown") {
 if (o.className == "Scrollbar-Track") o.style.backgroundColor = "#E3E3E3";
 else o.style.backgroundPosition = "bottom left";
 } else {
 if (o.className == "Scrollbar-Track") o.style.backgroundColor = "#EEE";
 else o.style.backgroundPosition = "top left";
 }
}


var scroller = null;
var scrollbar = null;
var scroller_width = 200;
var scroller_height = 473;
//var scrollTween = null;

window.onload = function () {
 if (document.getElementById("Container") && document.getElementById("Scrollbar-Container")) {

 scroller = new jsScroller(document.getElementById("Container"), scroller_width, scroller_height);
 scrollbar = new jsScrollbar (document.getElementById("Scrollbar-Container"), scroller, true, scrollbarEvent);
 // scrollTween = new jsScrollerTween (scrollbar, true);
 scrollbar._scrollDist = 10;
 }
};

/**
 * AJAX Upload ( http://valums.com/ajax-upload/ ) 
 * Copyright (c) Andris Valums
 * Licensed under the MIT license ( http://valums.com/mit-license/ )
 * Thanks to Gary Haran, David Mark, Corey Burns and others for contributions 
 */
(function () {
 /* global window */
 /* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true */
 
 /**
 * Wrapper for FireBug's console.log
 */
 function log(){
 if (typeof(console) != 'undefined' && typeof(console.log) == 'function'){ 
 Array.prototype.unshift.call(arguments, '[Ajax Upload]');
 console.log( Array.prototype.join.call(arguments, ' '));
 }
 } 

 /**
 * Attaches event to a dom element.
 * @param {Element} el
 * @param type event name
 * @param fn callback This refers to the passed element
 */
 function addEvent(el, type, fn){
 if (el.addEventListener) {
 el.addEventListener(type, fn, false);
 } else if (el.attachEvent) {
 el.attachEvent('on' + type, function(){
 fn.call(el);
 });
 } else {
 throw new Error('not supported or DOM not loaded');
 }
 } 
 
 /**
 * Attaches resize event to a window, limiting
 * number of event fired. Fires only when encounteres
 * delay of 100 after series of events.
 * 
 * Some browsers fire event multiple times when resizing
 * http://www.quirksmode.org/dom/events/resize.html
 * 
 * @param fn callback This refers to the passed element
 */
 function addResizeEvent(fn){
 var timeout;
 
 addEvent(window, 'resize', function(){
 if (timeout){
 clearTimeout(timeout);
 }
 timeout = setTimeout(fn, 100); 
 });
 } 
 
 // Needs more testing, will be rewriten for next version 
 // getOffset function copied from jQuery lib (http://jquery.com/)
 if (document.documentElement.getBoundingClientRect){
 // Get Offset using getBoundingClientRect
 // http://ejohn.org/blog/getboundingclientrect-is-awesome/
 var getOffset = function(el){
 var box = el.getBoundingClientRect();
 var doc = el.ownerDocument;
 var body = doc.body;
 var docElem = doc.documentElement; // for ie 
 var clientTop = docElem.clientTop || body.clientTop || 0;
 var clientLeft = docElem.clientLeft || body.clientLeft || 0;
 
 // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
 // while others are logical. Make all logical, like in IE8. 
 var zoom = 1; 
 if (body.getBoundingClientRect) {
 var bound = body.getBoundingClientRect();
 zoom = (bound.right - bound.left) / body.clientWidth;
 }
 
 if (zoom > 1) {
 clientTop = 0;
 clientLeft = 0;
 }
 
 var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;
 
 return {
 top: top,
 left: left
 };
 }; 
 } else {
 // Get offset adding all offsets 
 var getOffset = function(el){
 var top = 0, left = 0;
 do {
 top += el.offsetTop || 0;
 left += el.offsetLeft || 0;
 el = el.offsetParent;
 } while (el);
 
 return {
 left: left,
 top: top
 };
 };
 }
 
 /**
 * Returns left, top, right and bottom properties describing the border-box,
 * in pixels, with the top-left relative to the body
 * @param {Element} el
 * @return {Object} Contains left, top, right,bottom
 */
 function getBox(el){
 var left, right, top, bottom;
 var offset = getOffset(el);
 left = offset.left;
 top = offset.top;
 
 right = left + el.offsetWidth;
 bottom = top + el.offsetHeight;
 
 return {
 left: left,
 right: right,
 top: top,
 bottom: bottom
 };
 }
 
 /**
 * Helper that takes object literal
 * and add all properties to element.style
 * @param {Element} el
 * @param {Object} styles
 */
 function addStyles(el, styles){
 for (var name in styles) {
 if (styles.hasOwnProperty(name)) {
 el.style[name] = styles[name];
 }
 }
 }
 
 /**
 * Function places an absolutely positioned
 * element on top of the specified element
 * copying position and dimentions.
 * @param {Element} from
 * @param {Element} to
 */ 
 function copyLayout(from, to){
 var box = getBox(from);
 
 addStyles(to, {
 position: 'absolute', 
 left : box.left + 'px',
 top : box.top + 'px',
 width : from.offsetWidth + 'px',
 height : from.offsetHeight + 'px'
 }); 
 }

 /**
 * Creates and returns element from html chunk
 * Uses innerHTML to create an element
 */
 var toElement = (function(){
 var div = document.createElement('div');
 return function(html){
 div.innerHTML = html;
 var el = div.firstChild;
 return div.removeChild(el);
 };
 })();
 
 /**
 * Function generates unique id
 * @return unique id 
 */
 var getUID = (function(){
 var id = 0;
 return function(){
 return 'ValumsAjaxUpload' + id++;
 };
 })(); 
 
 /**
 * Get file name from path
 * @param {String} file path to file
 * @return filename
 */ 
 function fileFromPath(file){
 return file.replace(/.*(\/|\\)/, "");
 }
 
 /**
 * Get file extension lowercase
 * @param {String} file name
 * @return file extenstion
 */ 
 function getExt(file){
 return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
 }

 function hasClass(el, name){ 
 var re = new RegExp('\\b' + name + '\\b'); 
 return re.test(el.className);
 } 
 function addClass(el, name){
 if ( ! hasClass(el, name)){ 
 el.className += ' ' + name;
 }
 } 
 function removeClass(el, name){
 var re = new RegExp('\\b' + name + '\\b'); 
 el.className = el.className.replace(re, ''); 
 }
 
 function removeNode(el){
 el.parentNode.removeChild(el);
 }

 /**
 * Easy styling and uploading
 * @constructor
 * @param button An element you want convert to 
 * upload button. Tested dimentions up to 500x500px
 * @param {Object} options See defaults below.
 */
 window.AjaxUpload = function(button, options){
 this._settings = {
 // Location of the server-side upload script
 action: 'upload.php',
 // File upload name
 name: 'userfile',
 // Additional data to send
 data: {},
 // Submit file as soon as it's selected
 autoSubmit: true,
 // The type of data that you're expecting back from the server.
 // html and xml are detected automatically.
 // Only useful when you are using json data as a response.
 // Set to "json" in that case. 
 responseType: false,
 // Class applied to button when mouse is hovered
 hoverClass: 'hover',
 // Class applied to button when AU is disabled
 disabledClass: 'disabled', 
 // When user selects a file, useful with autoSubmit disabled
 // You can return false to cancel upload 
 onChange: function(file, extension){
 },
 // Callback to fire before file is uploaded
 // You can return false to cancel upload
 onSubmit: function(file, extension){
 },
 // Fired when file upload is completed
 // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
 onComplete: function(file, response){
 }
 };
 
 // Merge the users options with our defaults
 for (var i in options) {
 if (options.hasOwnProperty(i)){
 this._settings[i] = options[i];
 }
 }
 
 // button isn't necessary a dom element
 if (button.jquery){
 // jQuery object was passed
 button = button[0];
 } else if (typeof button == "string") {
 if (/^#.*/.test(button)){
 // If jQuery user passes #elementId don't break it 
 button = button.slice(1); 
 }
 
 button = document.getElementById(button);
 }
 
 if ( ! button || button.nodeType !== 1){
 throw new Error("Please make sure that you're passing a valid element"); 
 }
 
 if ( button.nodeName.toUpperCase() == 'A'){
 // disable link 
 addEvent(button, 'click', function(e){
 if (e && e.preventDefault){
 e.preventDefault();
 } else if (window.event){
 window.event.returnValue = false;
 }
 });
 }
 
 // DOM element
 this._button = button; 
 // DOM element 
 this._input = null;
 // If disabled clicking on button won't do anything
 this._disabled = false;
 
 // if the button was disabled before refresh if will remain
 // disabled in FireFox, let's fix it
 this.enable(); 
 
 this._rerouteClicks();
 };
 
 // assigning methods to our class
 AjaxUpload.prototype = {
 setData: function(data){
 this._settings.data = data;
 },
 disable: function(){ 
 addClass(this._button, this._settings.disabledClass);
 this._disabled = true;
 
 var nodeName = this._button.nodeName.toUpperCase(); 
 if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
 this._button.setAttribute('disabled', 'disabled');
 } 
 
 // hide input
 if (this._input){
 // We use visibility instead of display to fix problem with Safari 4
 // The problem is that the value of input doesn't change if it 
 // has display none when user selects a file 
 this._input.parentNode.style.visibility = 'hidden';
 }
 },
 enable: function(){
 removeClass(this._button, this._settings.disabledClass);
 this._button.removeAttribute('disabled');
 this._disabled = false;
 
 },
 /**
 * Creates invisible file input 
 * that will hover above the button
 * <div><input type='file' /></div>
 */
 _createInput: function(){ 
 var self = this;
 
 var input = document.createElement("input");
 input.setAttribute('type', 'file');
 input.setAttribute('name', this._settings.name);
 
 addStyles(input, {
 'position' : 'absolute',
 // in Opera only 'browse' button
 // is clickable and it is located at
 // the right side of the input
 'right' : 0,
 'margin' : 0,
 'padding' : 0,
 'fontSize' : '480px', 
 'cursor' : 'pointer'
 }); 

 var div = document.createElement("div"); 
 addStyles(div, {
 'display' : 'block',
 'position' : 'absolute',
 'overflow' : 'hidden',
 'margin' : 0,
 'padding' : 0, 
 'opacity' : 0,
 // Make sure browse button is in the right side
 // in Internet Explorer
 'direction' : 'ltr',
 //Max zIndex supported by Opera 9.0-9.2
 'zIndex': 2147483583
 });
 
 // Make sure that element opacity exists.
 // Otherwise use IE filter 
 if ( div.style.opacity !== "0") {
 if (typeof(div.filters) == 'undefined'){
 throw new Error('Opacity not supported by the browser');
 }
 div.style.filter = "alpha(opacity=0)";
 } 
 
 addEvent(input, 'change', function(){
 
 if ( ! input || input.value === ''){ 
 return; 
 }
 
 // Get filename from input, required 
 // as some browsers have path instead of it 
 var file = fileFromPath(input.value);
 
 if (false === self._settings.onChange.call(self, file, getExt(file))){
 self._clearInput(); 
 return;
 }
 
 // Submit form when value is changed
 if (self._settings.autoSubmit) {
 self.submit();
 }
 }); 

 addEvent(input, 'mouseover', function(){
 addClass(self._button, self._settings.hoverClass);
 });
 
 addEvent(input, 'mouseout', function(){
 removeClass(self._button, self._settings.hoverClass);
 
 // We use visibility instead of display to fix problem with Safari 4
 // The problem is that the value of input doesn't change if it 
 // has display none when user selects a file 
 input.parentNode.style.visibility = 'hidden';

 }); 
 
 div.appendChild(input);
 document.body.appendChild(div);
 
 this._input = input;
 },
 _clearInput : function(){
 if (!this._input){
 return;
 } 
 
 // this._input.value = ''; Doesn't work in IE6 
 removeNode(this._input.parentNode);
 this._input = null; 
 this._createInput();
 
 removeClass(this._button, this._settings.hoverClass);
 },
 /**
 * Function makes sure that when user clicks upload button,
 * the this._input is clicked instead
 */
 _rerouteClicks: function(){
 var self = this;
 
 // IE will later display 'access denied' error
 // if you use using self._input.click()
 // other browsers just ignore click()

 addEvent(self._button, 'mouseover', function(){
 if (self._disabled){
 return;
 }
 
 if ( ! self._input){
 self._createInput();
 }
 
 var div = self._input.parentNode; 
 copyLayout(self._button, div);
 div.style.visibility = 'visible';
 
 });
 
 
 // commented because we now hide input on mouseleave
 /**
 * When the window is resized the elements 
 * can be misaligned if button position depends
 * on window size
 */
 //addResizeEvent(function(){
 // if (self._input){
 // copyLayout(self._button, self._input.parentNode);
 // }
 //}); 
 
 },
 /**
 * Creates iframe with unique name
 * @return {Element} iframe
 */
 _createIframe: function(){
 // We can't use getTime, because it sometimes return
 // same value in safari :(
 var id = getUID(); 
 
 // We can't use following code as the name attribute
 // won't be properly registered in IE6, and new window
 // on form submit will open
 // var iframe = document.createElement('iframe');
 // iframe.setAttribute('name', id); 
 
 var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
 // src="javascript:false; was added
 // because it possibly removes ie6 prompt 
 // "This page contains both secure and nonsecure items"
 // Anyway, it doesn't do any harm. 
 iframe.setAttribute('id', id);
 
 iframe.style.display = 'none';
 document.body.appendChild(iframe);
 
 return iframe;
 },
 /**
 * Creates form, that will be submitted to iframe
 * @param {Element} iframe Where to submit
 * @return {Element} form
 */
 _createForm: function(iframe){
 var settings = this._settings;
 
 // We can't use the following code in IE6
 // var form = document.createElement('form');
 // form.setAttribute('method', 'post');
 // form.setAttribute('enctype', 'multipart/form-data');
 // Because in this case file won't be attached to request 
 var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
 
 form.setAttribute('action', settings.action);
 form.setAttribute('target', iframe.name); 
 form.style.display = 'none';
 document.body.appendChild(form);
 
 // Create hidden input element for each data key
 for (var prop in settings.data) {
 if (settings.data.hasOwnProperty(prop)){
 var el = document.createElement("input");
 el.setAttribute('type', 'hidden');
 el.setAttribute('name', prop);
 el.setAttribute('value', settings.data[prop]);
 form.appendChild(el);
 }
 }
 return form;
 },
 /**
 * Gets response from iframe and fires onComplete event when ready
 * @param iframe
 * @param file Filename to use in onComplete callback 
 */
 _getResponse : function(iframe, file){ 
 // getting response
 var toDeleteFlag = false, self = this, settings = this._settings; 
 
 addEvent(iframe, 'load', function(){ 
 
 if (// For Safari 
 iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
 // For FF, IE
 iframe.src == "javascript:'<html></html>';"){ 
 // First time around, do not delete.
 // We reload to blank page, so that reloading main page
 // does not re-submit the post.
 
 if (toDeleteFlag) {
 // Fix busy state in FF3
 setTimeout(function(){
 removeNode(iframe);
 }, 0);
 }
 
 return;
 }
 
 var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
 
 // fixing Opera 9.26,10.00
 if (doc.readyState && doc.readyState != 'complete') {
 // Opera fires load event multiple times
 // Even when the DOM is not ready yet
 // this fix should not affect other browsers
 return;
 }
 
 // fixing Opera 9.64
 if (doc.body && doc.body.innerHTML == "false") {
 // In Opera 9.64 event was fired second time
 // when body.innerHTML changed from false 
 // to server response approx. after 1 sec
 return;
 }
 
 var response;
 
 if (doc.XMLDocument) {
 // response is a xml document Internet Explorer property
 response = doc.XMLDocument;
 } else if (doc.body){
 // response is html document or plain text
 response = doc.body.innerHTML;
 
 if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
 // If the document was sent as 'application/javascript' or
 // 'text/javascript', then the browser wraps the text in a <pre>
 // tag and performs html encoding on the contents. In this case,
 // we need to pull the original text content from the text node's
 // nodeValue property to retrieve the unmangled content.
 // Note that IE6 only understands text/html
 if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
 response = doc.body.firstChild.firstChild.nodeValue;
 }
 
 if (response) {
 response = eval("(" + response + ")");
 } else {
 response = {};
 }
 }
 } else {
 // response is a xml document
 response = doc;
 }
 
 settings.onComplete.call(self, file, response);
 
 // Reload blank page, so that reloading main page
 // does not re-submit the post. Also, remember to
 // delete the frame
 toDeleteFlag = true;
 
 // Fix IE mixed content issue
 iframe.src = "javascript:'<html></html>';";
 }); 
 }, 
 /**
 * Upload file contained in this._input
 */
 submit: function(){ 
 var self = this, settings = this._settings;
 
 if ( ! this._input || this._input.value === ''){ 
 return; 
 }
 
 var file = fileFromPath(this._input.value);
 
 // user returned false to cancel upload
 if (false === settings.onSubmit.call(this, file, getExt(file))){
 this._clearInput(); 
 return;
 }
 
 // sending request 
 var iframe = this._createIframe();
 var form = this._createForm(iframe);
 
 // assuming following structure
 // div -> input type='file'
 removeNode(this._input.parentNode); 
 removeClass(self._button, self._settings.hoverClass);
 
 form.appendChild(this._input);
 
 form.submit();

 // request set, clean up 
 removeNode(form); form = null; 
 removeNode(this._input); this._input = null;
 
 // Get response from iframe and fire onComplete event when ready
 this._getResponse(iframe, file); 

 // get ready for next request 
 this._createInput();
 }
 };
})(); 

/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
* sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
* interval: 50, // number = milliseconds of polling interval
* over: showNav, // function = onMouseOver callback (required)
* timeout: 100, // number = milliseconds delay before onMouseOut function call
* out: hideNav // function = onMouseOut callback (required)
* });
* 
* @param f onMouseOver function || An object with configuration options
* @param g onMouseOut function || Nothing (use configuration options object)
* @return The object (aka "this") that called hoverIntent, and the event object
* @author Brian Cherne <brian@cherne.net>
*/
(function($) {
 $.fn.hoverIntent = function(f,g) {
 // default configuration options
 var cfg = {
 sensitivity: 7,
 interval: 1,
 timeout: 0
 };
 // override configuration options with user supplied object
 cfg = $.extend(cfg, g ? { over: f, out: g } : f );

 // instantiate variables
 // cX, cY = current X and Y position of mouse, updated by mousemove event
 // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
 var cX, cY, pX, pY;

 // A private function for getting mouse position
 var track = function(ev) {
 cX = ev.pageX;
 cY = ev.pageY;
 };

 // A private function for comparing current and previous mouse position
 var compare = function(ev,ob) {
 ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
 // compare mouse positions to see if they've crossed the threshold
 if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
 $(ob).unbind("mousemove",track);
 // set hoverIntent state to true (so mouseOut can be called)
 ob.hoverIntent_s = 1;
 return cfg.over.apply(ob,[ev]);
 } else {
 // set previous coordinates for next time
 pX = cX; pY = cY;
 // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
 ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
 }
 };

 // A private function for delaying the mouseOut function
 var delay = function(ev,ob) {
 ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
 ob.hoverIntent_s = 0;
 return cfg.out.apply(ob,[ev]);
 };

 // A private function for handling mouse 'hovering'
 var handleHover = function(e) {
 // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
 var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
 while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
 if ( p == this ) { return false; }

 // copy objects to be passed into t (required for event object to be passed in IE)
 var ev = jQuery.extend({},e);
 var ob = this;

 // cancel hoverIntent timer if it exists
 if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

 // else e.type == "onmouseover"
 if (e.type == "mouseover") {
 // set "previous" X and Y position based on initial entry point
 pX = ev.pageX; pY = ev.pageY;
 // update "current" X and Y position based on mousemove
 $(ob).bind("mousemove",track);
 // start polling interval (self-calling timeout) to compare mouse coordinates over time
 if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

 // else e.type == "onmouseout"
 } else {
 // unbind expensive mousemove event
 $(ob).unbind("mousemove",track);
 // if hoverIntent state is true, then call the mouseOut function after the specified delay
 if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
 }
 };

 // bind the function to the two event listeners
 return this.mouseover(handleHover).mouseout(handleHover);
 };
})(jQuery);

$(document).ready(function() {
 
 function addMega(){$(this).addClass("hovering");}
 function removeMega(){$(this).removeClass("hovering");}
 
 var megaConfig = {
 interval: 1,
 sensitivity: 4,
 over: addMega,
 timeout: 1,
 out: removeMega
 };
 
 $("div.mega").hoverIntent(megaConfig);
 
 $(".jm_col").mouseover(function(){
 $(this).css("background-position","top right");
 });
 $(".jm_col").mouseout(function(){
 $(this).css("background-position","top left");
 });
 
 
});
