var Public={
    // some popup variables
    popupWindow : null,
    popup: null,
    //variables for program plan on first page
    programChannel: 'kanal2',
    programDay: '0',
    gallerific_gallery: null,
    scrollBannerMove: 1,
    scrollBannerDirection: '',
    scrollBannerWidth: '',
    popupCloseTimer: null,
    searchTimer: null,
    galleryViewOpened:false,
    galleryViewOpenedIndex:0,

    selectRadio : function (el, input_id, value)
    {
        $('.'+input_id).removeClass('selected');
        $(el).addClass('selected');
        $('#'+input_id).val(value);
    },
    selectCheckbox : function (el, input_id, value)
    {
        $(el).toggleClass('selected');
        if ($(el).hasClass('selected'))
        {
            $('#'+input_id).val(value);
        }
        else
        {
            $('#'+input_id).val('');
        }
    },
    openPopupWindow : function (window_title, url, payload, width)
    {
        if ($('#popup_window_body').length == 0)
        {
            $('body').append('<div id="popup_window_body" class="popup_window_body"></div>');
        }

        if (!width)
            width = 600;

        if (!payload)
            payload = '';

        Common.load(url, 'popup_window_body', payload);

        $("#popup_window_body").dialog({
		title:     window_title,
		autoOpen:  false,
		resizable: false,
		width:     width,
		modal:     true,
		close: function(ev, ui) { $(this).dialog('destroy');}

	   });
	   $("#popup_window_body").dialog("open");

    },
    closePopupWindow : function ()
    {
        $("#popup_window_body").dialog("destroy");
    },
    Accordion : function ( accordion_id, item_id )
    {
	   $("."+accordion_id).removeClass('selected');
	   $("."+accordion_id+" + ."+accordion_id+"-"+item_id).addClass('selected');
    },
    OpenPopup : function (popup_id)
    {
        Public.closePopup();

        var pos = $("#anchor_" + popup_id).offset();

        //console.log(popup_id);

        $("#"+popup_id).css( { "position": "absolute", "left": (pos.left+2)+"px", "top": (pos.top+$("#anchor_"+popup_id).height()+5)+"px" } );
        $("#"+popup_id).show();
        $("#"+popup_id).bind('mouseover', Public.popupCancelTimer);
        $("#"+popup_id).bind('mouseout', Public.popupTimer);
        $("#"+popup_id+" .jscrollable").jScrollPane();
    },
    setSelectValue : function (dest, value, el, label)
    {
        if (!dest) return;

        $('#'+dest).val(value);

        $(el).parent().siblings().find('a').removeClass('selected');
        $(el).addClass('selected');

        Public.closePopup();

        if (value)
        {
            if (label)
            {
                $('#anchor_'+$(el).parent().parent().parent().parent().parent().attr('id')).html(label);
            }
            else
            {
                $('#anchor_'+$(el).parent().parent().parent().parent().parent().attr('id')).html(value);
            }
        }
    },
    setPopupProperContainer : function (id, tmp_id)
    {
        $('#temp_popups_container').append($('#'+tmp_id));
		$('#'+id).remove();
		$('#'+tmp_id).attr('id', id);

    },
    closePopup : function ()
    {
        $(".popup").hide();
        $(".popup").unbind('mouseover');
        $(".popup").unbind('mouseout');
    },
    popupTimer : function ()
    {
        if (Public.popupCloseTimer==null)
        {
            Public.popupCloseTimer = window.setTimeout(Public.closePopup, 300);
        }
    },
    popupCancelTimer : function()
    {
        if (Public.popupCloseTimer!=null)
        {
            window.clearTimeout(Public.popupCloseTimer);
            Public.popupCloseTimer = null;
	    }
    },
    newsSearchSubmit : function (source, value)
    {
        if (source == 'month')
        {
            $('#news_search_month').val(value);
        }
        if (source == 'year')
        {
            $('#news_search_year').val(value);
        }
        if (source == 'keyword')
        {
            if ($('#news_search_keyword').val() == 'Otsi...') return;
        }

        if ($('#news_search_keyword').val() == 'Otsi...')
        {
            $('#news_search_keyword').val('');
        }

        $('#news_search_form').submit();
    },
    channelProgramClickDay : function( day )
    {
        if($('#program-'+this.programChannel+'-'+day).html())
        {
            this.channelProgramDayClicked(day);
        }
        else
        {
            Common.load('program/firstpagelist', 'program-'+this.programChannel+'-'+day, 'channel='+this.programChannel+'&day='+day, function() {Public.channelProgramDayClicked(day);});
        }
    },
    channelProgramDayClicked : function( day )
    {
        $(".saatekavanavi .day").removeClass("selected");
        $(".saatekava .saatekavaheader .tabs .day").removeClass("selected");
        $("#saatekavanavi_"+day).addClass("selected");
        $("#saatekavatab_"+day).addClass("selected");
        this.programDay = day;

        $('.saatekavaheader div.day_date').css('display','none');
        $('#program-day-'+day).css('display','');

        this.channelProgramShow(this.programChannel, day);
    },
    channelProgramClickChannel : function ( channel )
    {
        if($('#program-'+channel+'-'+this.programDay).html())
        {
            this.channelProgramChannelClicked(channel);
        }
        else
        {
            Common.load('program/firstpagelist', 'program-'+channel+'-'+this.programDay, 'channel='+channel+'&day='+this.programDay, function() {Public.channelProgramChannelClicked(channel);});
        }
    },
    channelProgramChannelClicked : function ( channel )
    {
        if (channel=="kanal2")
        {
            $("#saatekava_channelselector_k2").attr("src","img/sidebar-saatekava-kanal-k2-1.png");
            $("#saatekava_channelselector_k11").attr("src","img/sidebar-saatekava-kanal-k11-0.png");
            $("#saatekava_channelselector_k12").attr("src","img/sidebar-saatekava-kanal-k12-0.png");
        }
        else if(channel=="kanal11")
        {
            $("#saatekava_channelselector_k2").attr("src","img/sidebar-saatekava-kanal-k2-0.png");
            $("#saatekava_channelselector_k11").attr("src","img/sidebar-saatekava-kanal-k11-1.png");
            $("#saatekava_channelselector_k12").attr("src","img/sidebar-saatekava-kanal-k12-0.png");
        } 
        else 
        {
        	$("#saatekava_channelselector_k2").attr("src","img/sidebar-saatekava-kanal-k2-0.png");
            $("#saatekava_channelselector_k11").attr("src","img/sidebar-saatekava-kanal-k11-0.png");
            $("#saatekava_channelselector_k12").attr("src","img/sidebar-saatekava-kanal-k12-1.png");
        }
        
        this.programChannel = channel;
        this.channelProgramShow(channel, this.programDay);
    },
    channelProgramShow: function(channel, day)
    {
        $('div.program_item').css('display','none');
        $('#program-'+channel+'-'+day).css('display','');
    },
    channelProgramPopup : function ( saade_id )
    {
        var pos = $("#saatekava_row_" + saade_id).offset();
        $("#saatekava_popup").css( { "position": "absolute", "left": (pos.left - 10) + "px", "top": (pos.top - 70) + "px" } );
        $("#saatekava_popup").show();
        $("#saatekava_popup_closebtn").css( { "position": "absolute", "left": (pos.left + 272) + "px", "top": (pos.top - 5) + "px" } );
        $("#saatekava_popup_closebtn").show();
    },
    channelProgramClosePopup : function()
    {
        $("#saatekava_popup").hide();
        $("#saatekava_popup_closebtn").hide();
    },
    galleryOpen : function (image_index, only_resize)
    {
        $('#slideshow').css('display','none');
        if (!only_resize)
        {
            Public.gallerific_gallery.gotoIndex(image_index,1);
            Public.galleryViewOpened = true;
        }

        setTimeout(function(){
            Public.galleryPictureOpenResize();

            if (image_index == Public.galleryViewOpenedIndex)
            {
                setTimeout(function(){
                    Public.galleryPictureOpenResize();

                    if (image_index == Public.galleryViewOpenedIndex)
                    {
                        setTimeout(function(){
                            Public.galleryPictureOpenResize();
                        },900);
                    }

                },900);
            }

        },900);





    },

    galleryPictureOpenResize : function ()
    {
        if (!Public.galleryViewOpened) return;

        var displayed_image = $('#slideshow .advance-link img');
        var image_browser_fit_height = $(window).height()*0.75;

        var displayed_image_height_orig = displayed_image.attr('height');

        if ((image_browser_fit_height > displayed_image_height_orig))
        {
            var displayed_image_height = displayed_image_height_orig;
            var displayed_image_width = displayed_image.attr('width');
        }
        else
        {
            var displayed_image_height = image_browser_fit_height;
            var ratio = displayed_image_height_orig / image_browser_fit_height;
            var displayed_image_width = displayed_image.attr('width') / ratio;

            displayed_image.height(displayed_image_height);
            displayed_image.width(displayed_image_width);
        }

	    // Position
	    var st=$(document).scrollTop();

	    // Overlay
        $("#gallery_overlay").css( { "position": "absolute", "left": "0px", "top": "0px" } );
        $("#gallery_overlay").width($(document).width());
        $("#gallery_overlay").height($(document).height());
        $("#gallery_overlay").show();

        // Img
        $("#gallery_imagecontainer").show();
        $("#gallery_image").css( { "height": ($(window).height()-200)+"px" });
        $("#gallery_imagecontainer").css( { "position": "absolute", "left": Math.round(($(window).width()-displayed_image_width)/2)+"px", "top": (st+40)+"px" } );
        $("#gallery_image").show();

        // Prev
        $("#gallery_prev").css( { "position": "absolute", "left": (Math.round(($(window).width()-displayed_image_width)/2)-20)+"px", "top": (Math.round(displayed_image_height/2)+20+st)+"px" } );
        $("#gallery_prev").show();

        // Next
        $("#gallery_next").css( { "position": "absolute", "left": (Math.round(($(window).width()-displayed_image_width)/2)+displayed_image_width-20)+"px", "top": (Math.round(displayed_image_height/2)+20+st)+"px" } );
        $("#gallery_next").show();

	    // Close
        $("#gallery_close").css( { "position": "absolute", "left": (Math.round(($(window).width()-displayed_image_width)/2)+displayed_image_width-20)+"px", "top": (st+20)+"px" } );
	    $("#gallery_close").show();

	    // Title
        $("#gallery_title").css( { "position": "absolute", "left": Math.round(($(window).width()-$("#gallery_title").width())/2)+"px", "top": (displayed_image_height+50+st)+"px" } );
	    $("#gallery_title").show();

	    // More
        $("#gallery_more").css( { "position": "absolute", "left": Math.round(($(window).width()-$("#gallery_more").width())/2)+"px", "top": (displayed_image_height+80+st)+"px" } );
	    $("#gallery_more").show();

	    // More: prev
        $("#gallery_more_prev").css( { "position": "absolute", "left": (Math.round(($(window).width()-$("#gallery_more").width())/2)-10)+"px", "top": (displayed_image_height+118+st)+"px" } );
	    $("#gallery_more_prev").show();

	    // More: next
        $("#gallery_more_next").css( { "position": "absolute", "left": (Math.round(($(window).width()-642)/2)+642-28)+"px", "top": (displayed_image_height+118+st)+"px" } );
	    $("#gallery_more_next").show();

	    $('#slideshow').css('display','');
    },

    GALLERYClose : function ()
    {
    	Public.galleryClose();
    },
    galleryClose : function ()
    {
       Public.galleryViewOpened = false;
	   $("#gallery_overlay").hide();
	   $("#gallery_imagecontainer").hide();
	   $("#gallery_title").hide();
	   $("#gallery_prev").hide();
	   $("#gallery_next").hide();
	   $("#gallery_close").hide();
	   $("#gallery_more").hide();
	   $("#gallery_more_prev").hide();
	   $("#gallery_more_next").hide();
    },
    galleryGallerificRun : function ()
    {
        // Initially set opacity on thumbs and add
				// additional styling for hover effect on thumbs
				var onMouseOutOpacity = 0.67;

				// Initialize Advanced Galleriffic Gallery
				var gallery = $('#thumbs').galleriffic({
					numThumbs:                 5,
					preloadAhead:              1,
					enableBottomPager:         false,
					imageContainerSel:         '#slideshow',
					controlsContainerSel:      '#controls',
					captionContainerSel:       '#gallery_title',
					renderNavControls:         true,

					prevLinkText:              '',
					nextLinkText:              '',
					nextPageLinkText:          'Next &rsaquo;',
					prevPageLinkText:          '&lsaquo; Prev',

					onSlideChange:             function(prevIndex, nextIndex) {
						// 'this' refers to the gallery, which is an extension of $('#thumbs')
						this.find('ul.thumbs').children()
							.eq(prevIndex).fadeTo('1', onMouseOutOpacity).end()
							.eq(nextIndex).fadeTo('1', 1.0);

						// Update the photo index display
						this.$captionContainer.find('div.photo-index')
							.html('Photo '+ (nextIndex+1) +' of '+ this.data.length);
						if (Public.gallerific_gallery) Public.galleryOpen(0,1);
                        if (Common.browser.name == 'opera')
                        {
						  if (Public.gallerific_gallery) Public.galleryOpen(0,1);
                        }
					},
					onPageTransitionOut:       function(callback) {
						this.fadeTo('1', 0.0, callback);
					},
					onPageTransitionIn:        function() {
						var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
						var nextPageLink = this.find('a.next').css('visibility', 'hidden');

						// Show appropriate next / prev page links
						if (this.displayedPage > 0)
							prevPageLink.css('visibility', 'visible');

						var lastPage = this.getNumPages() - 1;
						if (this.displayedPage < lastPage)
							nextPageLink.css('visibility', 'visible');

						this.fadeTo('1', 1.0);
					}
				});

				Public.gallerific_gallery = gallery;

				/**************** Event handlers for custom next / prev page links **********************/

				gallery.find('a.prev').click(function(e) {
					gallery.previousPage();
					e.preventDefault();
				});

				gallery.find('a.next').click(function(e) {
					gallery.nextPage();
					e.preventDefault();
				});


				$('#gallery_prev').click(function(){
				    $('.nav-controls .prev').trigger('click');
				});
				$('#gallery_next').click(function(){
				    $('.nav-controls .next').trigger('click');
				});


    },
    fullScreenBannerOpen : function (width, height)
    {
        if (width && height)
        {
          var displayed_image_width = parseInt(width);
		  var displayed_image_height = parseInt(height);
        }
        else
        {
          displayed_image = $('#full_screen_banner_img');
		  var displayed_image_width = displayed_image.attr('width');
		  var displayed_image_height = displayed_image.attr('height');
        }

	    // Position
        var doc_height = $(document).height();
        var st=Math.round(($(window).height()-displayed_image_height)/2);
        //var top_offset = Math.round(($(window).width()-displayed_image_width)/2);//doc_height - displayed_image_height - 180;

        // Img
        $("#full_screen_banner").css( {"left": Math.round(($(window).width()-displayed_image_width)/2)+"px", "top": ($(window).scrollTop() + $(window).height()/2 - displayed_image_height/2) +"px" } );
        $("#full_screen_banner").show();

        $(window).scroll(function()
        {
            $('#full_screen_banner').animate({top:($(window).scrollTop() + $(window).height()/2 - displayed_image_height/2)+"px" },{queue: false, duration: 3});
            $('#full_screen_banner_close').animate({top:($(window).scrollTop() + $(window).height()/2 - displayed_image_height/2-15)+"px" },{duration: 3});
        });

        $(window).resize(function()
        {
            $('#full_screen_banner').animate({top:($(window).scrollTop() + $(window).height()/2 - displayed_image_height/2)+"px" },{queue: false, duration: 3});
            $('#full_screen_banner_close').animate({top:($(window).scrollTop() + $(window).height()/2 - displayed_image_height/2-15)+"px" },{duration: 3});
        });

	    // Close
        $("#full_screen_banner_close").css( {"left": (Math.round(($(window).width()-displayed_image_width)/2)+displayed_image_width)+"px", "top": ($(window).scrollTop() + $(window).height()/2 - displayed_image_height/2 - 15)+"px" } );
	    $("#full_screen_banner_close").show();
    },
    fullScreenBannerClose : function ()
    {
        $("#full_screen_banner").hide();
	    $("#full_screen_banner_close").hide();
    },
    scrollBannerOpen : function (width, height, direction, repeat)
    {
        if (!width || !height || !direction) return;

        this.scrollBannerDirection = direction;

        // Img
        $("#scroll_banner").show();
        $("#scroll_banner").css('height', height + 10);
	    // Close

	    $("#scroll_banner_close").show();

	    if (repeat)
	    {
	       $('#scroll_banner_close').animate({top:($(window).scrollTop() + $(window).height() - height - 20)+"px" },{duration: 3});
	       $('#scroll_banner').animate({top:($(window).scrollTop() + $(window).height() - height-10)+"px" },{queue: false, duration: 3});
	    }
	    else
	    {
	       $('#scroll_banner').animate({top:($(window).scrollTop() + $(window).height() - height - 10)+"px" },{queue: false, duration: 3});
	    }

        $(window).scroll(function()
        {
            if (repeat)
            {
                $('#scroll_banner_close').animate({top:($(window).scrollTop() + $(window).height() - height - 20)+"px" },{duration: 3});
                $('#scroll_banner').animate({top:($(window).scrollTop() + $(window).height() - height-10)+"px" },{queue: false, duration: 3});
            }
            else
            {
                $('#scroll_banner').animate({top:($(window).scrollTop() + $(window).height() - height - 10)+"px" },{queue: false, duration: 3});
            }
        });

        $(window).resize(function()
        {
            if (repeat)
            {
                $('#scroll_banner_close').animate({top:($(window).scrollTop() + $(window).height() - height - 20)+"px" },{duration: 3});
                $('#scroll_banner').animate({top:($(window).scrollTop() + $(window).height() - height-10)+"px" },{queue: false, duration: 3});
            }
            else
            {
                $('#scroll_banner').animate({top:($(window).scrollTop() + $(window).height() - height - 10)+"px" },{queue: false, duration: 3});
            }
        });
        if (repeat)
        {
            $( "#scroll_banner" ).imageScroller( {direction: direction} );
        }
        else
        {
            this.scrollBannerWidth = width;
            if (this.scrollBannerDirection == 'right')
            {
                $('#scroll_banner_item').css('left', 0 - width);
            }
            else
            {
                $('#scroll_banner_item').css('right', 0 - width);
            }
            setInterval("Public.scrollBanner()", 80);
        }
    },
    scrollBannerClose : function ()
    {
        this.scrollBannerMove = 0;
        $("#scroll_banner").remove();
	    $("#scroll_banner_close").remove();

    },
    scrollBanner : function()
    {
        if (!Public.scrollBannerMove) return;

        if (this.scrollBannerDirection == 'right')
        {
            if ($('#scroll_banner_item').offset().left >= $(window).width())
            {
                $('#scroll_banner_item').css('left', 0);
            }
            else
            {
                $('#scroll_banner_item').css('left', $('#scroll_banner_item').offset().left + 4);
                $('#scroll_banner_close').css('left', $('#scroll_banner_item').offset().left + this.scrollBannerWidth + 10);
            }
        }
        else
        {
            var right_offset = parseInt($('#scroll_banner_item').css('right'));
            if (right_offset >= $(window).width())
            {
                $('#scroll_banner_item').css('right', 0);
            }
            else
            {
                $('#scroll_banner_item').css('right', right_offset + 4);
                $('#scroll_banner_close').css('right', right_offset - 20);
            }
        }
    },

    toggleTelecastGalleryPagesNav : function()
    {
        if($('#tel_gal_pre_thumbs .pagination a[title=prev]').length)
        {
            $('#prev_gal_block').fadeIn();
        }
        else
        {
            $('#prev_gal_block').fadeOut();
        }
        if($('#tel_gal_pre_thumbs .pagination a[title=next]').length)
        {
            $('#next_gal_block').fadeIn();
        }
        else
        {
            $('#next_gal_block').fadeOut();
        }
    },
    RatingMouseOver: function ( rating_id, rating_value )
    {
	   $(".rating-"+rating_id).attr('src','img/star-0.png');
	   for(i=1;i<=rating_value;++i)
	   {
		  $(".rating-"+rating_id+"-"+i).attr('src','img/star-a.png');
	   }
    },
    RatingMouseOut: function ( rating_id, rating_value )
    {
	   $(".rating-"+rating_id).attr('src','img/star-0.png');
	   for(i=1;i<=rating_value;++i)
	   {
		  $(".rating-"+rating_id+"-"+i).attr('src','img/star-1.png');
	   }
    },
    setRating: function ( rating_id, rating_value,telecastid)
    {
        $('.rating-'+rating_id).removeAttr('onmouseover');
        $('.rating-'+rating_id).removeAttr('onmouseout');
        $('.rating-'+rating_id).removeAttr('onclick');

	    Common.postNoReload('telecasts/rate', null, 'telecastid='+telecastid+'&value='+rating_value.toString(), function () {});
    },
    setParticipantRating: function ( rating_id, rating_value, participantid)
    {
        $('.rating-'+rating_id).removeAttr('onmouseover');
        $('.rating-'+rating_id).removeAttr('onmouseout');
        $('.rating-'+rating_id).removeAttr('onclick');

	    Common.postNoReload('participants/rate', null, 'participantid='+participantid+'&value='+rating_value.toString(), function () {});
    },
    setVideoRating: function ( rating_id, rating_value,videoid)
    {
        $('.rating-'+rating_id).removeAttr('onmouseover');
        $('.rating-'+rating_id).removeAttr('onmouseout');
        $('.rating-'+rating_id).removeAttr('onclick');

	    Common.postNoReload('video/rate', null, 'videoid='+videoid+'&value='+rating_value.toString(), function () {});
    },
    tabbedClick: function ( tabbed_id, num )
    {
	   $("#tabbed_bar_"+tabbed_id+" .tab").removeClass("tab-selected");
	   $("#tabbed_bar_"+tabbed_id+" .tabclose").removeClass("tabclose-selected");
	   $("#tabbed_bar_"+tabbed_id+" .tab"+num).addClass("tab-selected");
	   $("#tabbed_bar_"+tabbed_id+" .tabclose"+num).addClass("tabclose-selected");
	   $("#tabbed_content_"+tabbed_id+" .content").fadeOut(300);
	   setTimeout(function(){$("#tabbed_content_"+tabbed_id+" .content"+num).fadeIn();},300);
    },
    tabbedClickVideo: function ( tabbed_id, num )
    {
	   $("#tabbed_bar_"+tabbed_id+" .link").removeClass("selected");
	   $("#tabbed_bar_"+tabbed_id+" .right").removeClass("selected");
	   $("#tabbed_bar_"+tabbed_id+" .tab"+num).addClass("selected");
	   $("#tabbed_bar_"+tabbed_id+" .tabclose"+num).addClass("selected");
	   $("#tabbed_content_"+tabbed_id+" .vid_content").fadeOut(300);
	   setTimeout(function(){$("#tabbed_content_"+tabbed_id+" .vid_content"+num).fadeIn();},300);

	   if (!$("#tabbed_content_"+tabbed_id+" .vid_content"+num).html())
	   {
	       if (num == 2) Common.load('video/nettvembed?telecast_id='+$('#telecast_id').val(),'tabbed_content_'+tabbed_id+' .vid_content'+num);
	       if (num == 3) Common.load('video/telecasts','tabbed_content_'+tabbed_id+' .vid_content'+num);
	       if (num == 4) Common.load('video/nettvembedall?sort=viewed','tabbed_content_'+tabbed_id+' .vid_content'+num);
	       if (num == 5) Common.load('video/nettvembedall?sort=added','tabbed_content_'+tabbed_id+' .vid_content'+num);
	       if (num == 6) Common.load('video/lemmikud','tabbed_content_'+tabbed_id+' .vid_content'+num);
	   }
	   setTimeout(function(){Common.toAnchor('video_tabs');},330);
    },
    rotateFilms: function ( tabbed_id, num )
    {
	   $("#tabbed_content_"+tabbed_id+" .content").fadeOut(300);
	   setTimeout(function(){$("#tabbed_content_"+tabbed_id+" .content"+num).fadeIn();},300);
    },
    voteGallup : function (id)
    {
       var items = Common.getInputsDataInArray('gallup_choice');
       if (items)
       {

           if (id)
           {
               Common.load('gallups/vote','gallup_c_block_'+id, $('#gallups_form_'+id).serialize());
           }
           else
           {
               $('#gallup_answer_button').fadeOut();
	           Common.load('gallups/vote','gallup_answers', $('#gallups_form').serialize());
           }
       }
    },
    voteGallupCenter : function (id)
    {
       var items = Common.getInputsDataInArray('gallup_choice');
       if (items)
       {
           if (id)
           {
               Common.load('gallups/vote','gallup_c_block_'+id, $('#gallups_form_center_'+id).serialize());
           }
           else
           {
               $('#gallup_answer_button').fadeOut();
	           Common.load('gallups/vote','gallup_answers', $('#gallups_form_center').serialize());
           }
       }
    },
    switcherClick : function ( switcher_id, num ,stop_timer)
    {
	   $("#switcher_"+switcher_id+" .link").removeClass("selected");
	   $("#switcher_"+switcher_id+" .link"+num).addClass("selected");
	   $("#switcher_"+switcher_id+" .img").hide();
	   $("#switcher_"+switcher_id+" .img"+num).show();
	   $("#switcher_"+switcher_id+" .description").hide();
	   $("#switcher_"+switcher_id+" .description"+num).show();

	   if (stop_timer && GlobalVars.fpb_timer)
	   {
	       clearInterval(GlobalVars.fpb_timer);
	   }
    },
    postComment: function (wide, el)
    {
    	$('#comment_saving').show();
    	$(el).hide();
        Common.postEditFormNoReload('comments/post', 'comments_msg',$('#comment_input_form'),null,null, function(){
            $('#comment_username_input').val('');
            $('#comment_email_input').val('');
            $('#comment_content_input').val('');
            Common.load('comments/showlist?owner=' + $('#comment_owner_input').val() + '&owner_id=' + $('#comment_owner_id_input').val()+((wide)?'&tpl=wide':''),'comments_list_block',null,function(){

            	$('#comment_saving').hide();
            	$(el).show();

            });

        },
        function(){

        		$('#comment_saving').hide();
            	$(el).show();
            }
        );
    },
    addProgram: function (id, id2)
    {
        Common.postEditFormNoReload('program/add', '', $('#add_program_form'))
        if (id)
        {
            $('#add_program_'+id).hide();
            $('#remove_program_'+id).show();

        }
        if (id2 && $('#add_program_type').val() == 'telecast')
        {
                $('.add_program_'+id2).hide();
                $('.remove_program_'+id2).show();
        }

        Public.closePopupWindow();
    },
    removeProgram: function (id, id2, reload)
    {
        if (reload == '1')
        {
            Common.postEditForm('program/remove', '', $('#remove_program_form'));
        }
        else
        {
            Common.postEditFormNoReload('program/remove', '', $('#remove_program_form'))
            if (id || id2)
            {
                if (id)
                {
                    $('#add_program_'+id).show();
                    $('#remove_program_'+id).hide();
                }
                if (id2 && $('#remove_program_type').val() == 'telecast')
                {
                    $('.add_program_'+id2).show();
                    $('.remove_program_'+id2).hide();
                }
            }
            Public.closePopupWindow();
        }
    },
    searchInputClick: function (el)
    {
        if ($(el).val() == 'Otsi...')
            $(el).val('');
    },
    typeAheadFilms:function(el)
    {
        if ($(el).val().length < 3) return;

        $('#typeahead_search_animation').show();

        if (Public.searchTimer)
		{
			clearTimeout(Public.searchTimer);
		}
		Public.searchTimer = setTimeout(function(){
		    Common.load('telecasts/typeaheadfilmssearch','type_ahead_search', 'search='+$(el).val(),
		    function(){
                var o = $("#films_search_keyword").offset();
                $("#type_ahead_search").css( { "position": "absolute", "left": (o.left+2)+"px", "top": (o.top+30)+"px" } );
		        $('#type_ahead_search').fadeIn();
		        $('#typeahead_search_animation').hide();

		    });
		}, 1500);
    },

    typeAheadCommon:function(el)
    {
        if ($(el).val().length < 3) return;

        $('#typeahead_search_animation_common').show();

        if (Public.searchTimer)
		{
			clearTimeout(Public.searchTimer);
		}
		Public.searchTimer = setTimeout(function(){
		    Common.load('telecasts/typeaheadcommonsearch','type_ahead_search', 'search='+$(el).val(),
		    function(){
                var o = $("#common_search_keyword").offset();
                $("#type_ahead_search").css( { "position": "absolute", "left": (o.left+2)+"px", "top": (o.top+30)+"px" } );
		        $('#type_ahead_search').fadeIn();
		        $('#typeahead_search_animation_common').hide();

		    });
		}, 1500);
    },

    typeAheadNews:function(el)
    {
        if ($(el).val().length < 3) return;

        $('#typeahead_search_animation').show();

        if (Public.searchTimer)
		{
			clearTimeout(Public.searchTimer);
		}
		Public.searchTimer = setTimeout(function(){
		    Common.load('news/typeaheadsearch','type_ahead_search', 'search='+$(el).val() + '&year=' + $('#news_search_year').val() + '&month=' + $('#news_search_month').val(),
		    function(){

		        var o = $("#news_search_keyword").offset();
                $("#type_ahead_search").css( { "position": "absolute", "left": (o.left+2)+"px", "top": (o.top+30)+"px" } );
		        $('#type_ahead_search').fadeIn();
		        $('#typeahead_search_animation').hide();

		    });
		}, 1500);
    },
    typeAheadUsers:function(el)
    {
        if ($(el).val().length < 3) return;

        $('#typeahead_search_animation').show();

        if (Public.searchTimer)
		{
			clearTimeout(Public.searchTimer);
		}
		Public.searchTimer = setTimeout(function(){
		    Common.load('users/typeaheadsearch','type_ahead_search', 'search='+$(el).val() ,
		    function(){

		        var o = $("#users_search_keyword").offset();
                $("#type_ahead_search").css( { "position": "absolute", "left": (o.left+2)+"px", "top": (o.top+30)+"px" } );
		        $('#type_ahead_search').fadeIn();
		        $('#typeahead_search_animation').hide();

		    });
		}, 1500);
    },
    setBookmark: function ()
    {
        title = 'Kanal 2';
        url = GlobalVars.base_url;

    	if (window.sidebar) { // Mozilla Firefox Bookmark
	       	window.sidebar.addPanel(title, url,"");
	    } else if( window.external ) { // IE Favorite
    		window.external.AddFavorite( url, title); }
    	else if(window.opera && window.print) { // Opera Hotlist
	       	return true;
    	}
    },
    addVideoToFavorites: function (video_id)
    {
        if (!video_id) return;

        if (video_id)
        {
            $('#add_video_'+video_id).hide();
            $('#remove_video_'+video_id).show();
        }
        Common.postNoReload('video/addtofavorites', null, 'video_id='+video_id);
    },


    addVideoToFavoritesByClass: function (video_id)
    {
        if (!video_id) return;

        if (video_id)
        {
            $('.add_video_'+video_id).hide();
            $('.remove_video_'+video_id).show();
        }
        Common.postNoReload('video/addtofavorites', null, 'video_id='+video_id);
    },


    removeVideoFromFavorites: function (video_id)
    {
        if (!video_id) return;

        if (video_id)
        {
            $('#add_video_'+video_id).show();
            $('#remove_video_'+video_id).hide();
        }
        Common.postAndReload('video/removefromfavorites', null, 'video_id='+video_id+'&remove=1');
    },

    removeVideoFromFavoritesNoReload: function (video_id)
    {
        if (!video_id) return;

        if (video_id)
        {
            $('#add_video_'+video_id).show();
            $('#remove_video_'+video_id).hide();
        }
        Common.postNoReload('video/removefromfavorites', null, 'video_id='+video_id+'&remove=1');
    },

    removeVideoFromFavoritesNoReloadByClass: function (video_id)
    {
        if (!video_id) return;

        if (video_id)
        {
            $('.add_video_'+video_id).show();
            $('.remove_video_'+video_id).hide();
        }
        Common.postNoReload('video/removefromfavorites', null, 'video_id='+video_id+'&remove=1');
    },

    pressSearchSubmit : function (source, value)
    {
        if (source == 'month')
        {
            $('#press_search_month').val(value);
        }
        if (source == 'year')
        {
            $('#press_search_year').val(value);
        }
        $('#press_search_form').submit();
    },
    videoDescrOpen :function()
    {
        $('#open_block_link').hide();
        $('#close_block_link').show();
        $('#video_descr_block').show();
        $('#closed_time_block').hide();
    },
    videoDescrClose :function()
    {
        $('#open_block_link').show();
        $('#close_block_link').hide();
        $('#video_descr_block').hide();

        $('#closed_time_block').show();
    },

    DROPDOWNCloseTimer : null,

	DROPDOWNOpen : function ( dropdown_id )
	{
		
		Public.DROPDOWN_CancelTimer();
		Public.DROPDOWN_Close();
		
		if(dropdown_id == "vaatasaateid") {
			$("#menuright_"+dropdown_id).addClass("open_sateid");
			$("#menu_"+dropdown_id).addClass("open_sateid");
		} else {
			$("#menuright_"+dropdown_id).addClass("open");
			$("#menu_"+dropdown_id).addClass("open");
		}
		
	    var pos = $("#menu").offset();
	    $("#dropdown_"+dropdown_id).css( { "position": "absolute", "left": (pos.left - 40) + "px", "top": (pos.top + 47) + "px" } );
		$("#dropdown_"+dropdown_id).show();
		$("#menu_"+dropdown_id).bind('mouseover',Public.DROPDOWN_CancelTimer);
		$("#menu_"+dropdown_id).bind('mouseout',Public.DROPDOWN_Timer);
		$("#menuright_"+dropdown_id).bind('mouseover',Public.DROPDOWN_CancelTimer);
		$("#menuright_"+dropdown_id).bind('mouseout',Public.DROPDOWN_Timer);
	    $("#dropdown_"+dropdown_id).bind('mouseover',Public.DROPDOWN_CancelTimer);
	    $("#dropdown_"+dropdown_id).bind('mouseout',Public.DROPDOWN_Timer);
	},

	DROPDOWN_Close: function ()
	{
		$("#menu div").removeClass("open");
		$(".dropdown").hide();
		$(".dropdownclosebtn").hide();
		$("#menu div").unbind('mouseover');
	    $(".dropdown").unbind('mouseover');
	    $(".dropdown").unbind('mouseout');
	},

	DROPDOWN_CancelTimer: function()
	{
		if (Public.DROPDOWNCloseTimer!=null)
		{
			window.clearTimeout(Public.DROPDOWNCloseTimer);
	    	Public.DROPDOWNCloseTimer = null;
		}
	},

	DROPDOWN_Timer : function()
	{
		if (Public.DROPDOWNCloseTimer==null)
		{
			Public.DROPDOWNCloseTimer = window.setTimeout(Public.DROPDOWN_Close, 300);
		}
	},
	MODULEToggle : function ( module_id )
	{
		$("#"+module_id+" .modulecontent").toggle();
	},

	TOOLTIPShow : function ( anchor, tooltip_text )
	{
		$("#tooltip .tooltipcontent").text(tooltip_text);
	  	var pos = $(anchor).offset();

		$("#tooltip").css( { "position": "absolute", "left": (pos.left-Math.round($("#tooltip").width())-6)+"px", "top": (pos.top+20)+"px" } );
	 	$("#tooltip").show();
	},

	TOOLTIPHide : function()
	{
		$("#tooltip").hide();
	},

	ACCORDIONClick : function ( accordion_id, item_id )
	{
		$("."+accordion_id).removeClass('selected');
		$("."+accordion_id+" + ."+accordion_id+"-"+item_id).addClass('selected');
	},

	PRESSIKLIENTMENUClick : function ( menu_id )
	{
		$(".saatedsidebarblock").removeClass('selected');
		$(".pressiklientsidebaropenblockheader").hide();
		$(".pressiklientsidebaropenblock").hide();
		$("#block_"+menu_id).addClass('selected');
		$("#header_"+menu_id).show();
		$("#content_"+menu_id).show();
		Common.toAnchor('anchor_'+menu_id);
	},

	PRESSIKLIENTMENUSubMenuClick : function ( item_id )
	{
		$(".pressiklientsidebaropenblock .link").removeClass('selected');
		$(".pressiklientsidebaropenblock .secondlevelwrapper").hide();
		$("#secondlevellink_"+item_id).addClass('selected');
		$("#secondlevel_"+item_id).show();
	}

}

var TABBEDCAROUSEL = {

	carouselID: '',
	carouselSelectedTab: '',

	container: function(){
		return $("#"+this.carouselID+'_container');
	},

	reload: function(){
		this.container().children().each(function(i,elem){$(elem).remove();});
		this.container().html('<div id="'+this.carouselID+'_carousel" class="jcarousel-skin-module785"><ul></ul></div>');
	},

	init: function(id, selected_tab){
		this.carouselID = id;
		this.carouselSelectedTab = selected_tab;
		$("#tabbed_bar_"+id+" .tab").removeClass("tab-selected");
		$("#tabbed_bar_"+id+" .tabclose").removeClass("tabclose-selected");
		$("#tabbed_bar_"+id+" .tab"+selected_tab).addClass("tab-selected");
		$("#tabbed_bar_"+id+" .tabclose"+selected_tab).addClass("tabclose-selected");
		TABBEDCAROUSEL.reload();
		$('#'+this.carouselID+'_carousel').jcarousel({
			itemLoadCallback: this.itemLoadCallback,
			start: 1
		});
	},

	itemLoadCallback: function(carousel, state){
		if (carousel.has(carousel.first, carousel.last)) return;
		var items = $('#'+TABBEDCAROUSEL.carouselID+'_tab'+TABBEDCAROUSEL.carouselSelectedTab+' li');
		for (i = 0; i < items.length; i++) {
			carousel.add(i+1, $(items[i]).html());
		}
		carousel.size(items.length);
	}

};

var dd = function (cfg) {
	this.config = cfg;
	this.runtime = {};
	this.runtime.container = null;
	this.runtime.datalist = null;
	this.runtime.body = null;
	this.runtime.isOpen = false;
	this.runtime.valueRef = null;

	this.init();
};

dd.prototype.init = function () {
	var self = this;
	this.runtime.datalist = $("#" + this.config.containerID + " .dropdown_datalist");
	this.runtime.container = $("#" + this.config.containerID + " .dropdown_container");
	this.runtime.body = $("#" + this.config.containerID + " .dropdown_container .dropdown_body_inner");
	var opts = $("#" + this.config.containerID + " .dropdown_datalist .dropdown_datalist_option");

	opts.each(function () {
		if ($(this).hasClass("selected")) {
			self.select(this);
		}

		$(this).click(function () {
			if (self.select(this)) {
				self.collapse();
			}
		});
		$(this).mouseover(function () {
			$(this).addClass("mover");
		});
		$(this).mouseout(function () {
			$(this).removeClass("mover");
		});
	});

	this.runtime.container.click(function () {
		if (self.isOpen()) {
			self.collapse();
		} else {
			self.expand();
		}
	});
};

dd.prototype.select = function (opt) {
	if (this.beforeSelect(opt)) {
		var changed = false;

		if (opt != this.runtime.valueRef) {
			$(this.runtime.valueRef).removeClass("selected");
			changed = true;
		}
		this.runtime.valueRef = opt;
		$(opt).addClass("selected");

		this.runtime.body.html($(opt).html());
		return this.afterSelect(opt, changed);
	}
};

dd.prototype.getValue = function () {
	return this.runtime.valueRef.getAttribute("__dd_opt_id");
};

dd.prototype.isOpen = function () {
	return this.runtime.isOpen;
};

dd.prototype.expand = function () {
	this.runtime.isOpen = true;
	this.runtime.container.addClass("container_open");
	this.runtime.datalist.css({display : "block"});
};

dd.prototype.collapse = function () {
	this.runtime.isOpen = false;
	this.runtime.container.removeClass("container_open");
	this.runtime.datalist.css({display : "none"});
};

dd.prototype.beforeSelect = function (opt) { return true };
dd.prototype.afterSelect = function (opt) { return true };

var ddFactory = {
	instances : {}
};

ddFactory.create = function (cfg) {
	if (!(cfg instanceof Object)) throw "Invalid configuration object";
	if (!("containerID" in cfg)) throw "ContainerID not specified";
	if (0 == $("#" + cfg.containerID).length) throw "Container element not found";

	this.instances[cfg.containerID] = new dd(cfg);
	return cfg.containerID;
};

ddFactory.getDDByResourceID = function (resID) {
	if (!(resID in this.instances)) {
		throw "Invalid resourceID";
	}

	return this.instances[resID];
};
