//function loadPhotoGallery(){
$.fn.loadPhotoGallery = function(options){
    options = $.extend({
        view: 5
    }, options);
/**
* navR,navL are flags for controlling the albums navigation first gives us the position of the album on the 
* left positions are the left positions for each of the X albums displayed at a time
*/  
    var $ps_albums = $(this);

    var navR,navL = false;
    var first = 1;
    var n_albums = options.view;
    var positions = {'0': 0};

    for (var i=1; i < n_albums; i++){
        positions[i] = positions[i-1] + 170;
    }

    var elems = $ps_albums.children().length;                      // number of albums available
    var slider_width = positions[n_albums-1] + 165;
    var $ps_slider = $('#ps_slider').css('width', slider_width);
				
    /*** let's position all the albums on the right side of the window */
    var hiddenRight = $(window).width() - $ps_albums.offset().left;
    $ps_albums.children('div').css('left',hiddenRight + 'px');
				
    /*** move the first X albums to the view port */
    $ps_albums.children('div:lt('+ n_albums +')').each(function(i) {
        var $elem = $(this);
        $elem.animate({
            'left': positions[i] + 'px',
            'opacity':1
        },800,function(){
            if(elems > n_albums)
                enableNavRight();
        });
    });
    /*** next album */
    $ps_slider.find('.next').bind('click',function(){
        if(!$ps_albums.children('div:nth-child('+ parseInt(first+ n_albums) +')').length || !navR) return;
        disableNavRight();
        disableNavLeft();
        moveRight();
    });
				
    /**
* we move the first album (the one on the left) to the left side of the window the next 4 albums slide one 
* position, and finally the next one in the list slides in, to fill the space of the first one
*/
    function moveRight () {
        var hiddenLeft = $ps_albums.offset().left + 163;					
        var cnt = 0;
    
        $ps_albums.children('div:nth-child('+first+')').animate({
            'left': - hiddenLeft + 'px', 
            'opacity':0
        },500,function(){
            $ps_albums.children('div').slice(first,parseInt(first+(n_albums-1))).each(function(i){
                var $elem = $(this);
                $elem.animate({
                    'left': positions[i] + 'px'
                    },800,function(){
                    ++cnt;
                    if(cnt == (options.view-1)){
                        $ps_albums.children('div:nth-child('+parseInt(first+n_albums)+')').animate({
                            'left': positions[cnt] + 'px',
                            'opacity':1
                        },500,function(){
                            ++first;
                            if(parseInt(first + (n_albums-1)) < elems)
                                enableNavRight();
                                enableNavLeft();
                        });
                    }		
                });
            }
            );		
        });
    }
    /***previous album */
    $ps_slider.find('.prev').bind('click',function(){
        if(first==1  || !navL) return;
        disableNavRight();
        disableNavLeft();
        moveLeft();
    });
				
    /**
* we move the last album (the one on the right) to the right side of the window the previous 4 albums slide one
*  position, and finally the previous one in the list slides in, to fill the space of the last one
*/
    function moveLeft () {
        var hiddenRight = $(window).width() - $ps_albums.offset().left;				
        var cnt = 0;
        var last= first+ (n_albums-1);
    
        $ps_albums.children('div:nth-child('+last+')')
            .animate({
                'left': hiddenRight + 'px',
                'opacity':0
            },500,function(){
            $ps_albums.children('div').slice(parseInt(last-n_albums),parseInt(last-1)).each(function(i){
                var $elem = $(this);
                $elem.animate({
                    'left': positions[i+1] + 'px'
                    },800,function(){
                    ++cnt;
                    if(cnt == (n_albums-1)){
                        $ps_albums.children('div:nth-child('+parseInt(last-n_albums)+')').animate({
                            'left': positions[0] + 'px',
                            'opacity':1
                        },500,function(){
                            //$this.hide();
                            --first;
                            enableNavRight();
                            if(first > 1)
                                enableNavLeft();
                        });
                    }										
                });
            }
            );
        });
    }
				
    /*** disable or enable albums navigation */
    function disableNavRight () {
        navR = false;
        $ps_slider.find('.next').addClass('disabled');
    }
    function disableNavLeft () {
        navL = false;
        $ps_slider.find('.prev').addClass('disabled');
    }
    function enableNavRight () {
        navR = true;
        $ps_slider.find('.next').removeClass('disabled');
    }
    function enableNavLeft () {
        navL = true;
        $ps_slider.find('.prev').removeClass('disabled');
    }	

    //Building photo container
    var $ps_container = $('#ps_container');
    var $ps_overlay = $('#ps_overlay');
    var $ps_close = $('#ps_close');
//    var $ps_title = $('#ps_title');

    /**
* when we click on an album, we load with AJAX the list of pictures for that album. we randomly rotate them 
* except the last one, which is the one the User sees first. We also resize and center each image.
*/
    $ps_albums.children('div').bind('click',function(){
        var $elem = $(this);
//        var album_name 	= 'album' + parseInt($elem.index() + 1);
        var $loading = $('<div />',{className:'loading'});
        
        $elem.append($loading);
        $ps_container.find('img').remove();
        var album_id = parseInt($elem.attr('album'));
        $.get('resources/ajax_photostack.php', {album_id:album_id} , function(data) {
            var items_count = data.length;
            for(var i = 0; i < items_count; ++i){
//                var item_source = data[i].path;
                var item_source = data[i];
//                var item_title = data[i].title;
//                var $title = $('<span>').attr('text', item_title);
                var cnt = 0;
                $('<img />').load(function(){
                    var $image = $(this);
//                    var $title = '<span>'+item_title+'</span>';     //pgk
//                    $title.css({'visibility':'hidden'});            //pgk
                    ++cnt;
                    resizeCenterImage($image);
                    $ps_container.append($image);
//                    $ps_title.append($title);
//                    $ps_title.append('<span>'+item_title+'</span>'); //pgk
                    var r = Math.floor(Math.random()*41)-20;
                    if(cnt < items_count){
                        $image.css({
                            '-moz-transform'	:'rotate('+r+'deg)',
                            '-webkit-transform'	:'rotate('+r+'deg)',
                            '-o-transform'      :'rotate('+r+'deg)',
                            'transform'		:'rotate('+r+'deg)'
                        });
                    }
                    
                    if(cnt == items_count){
                        currWindow = $(window).scrollTop();
                        $loading.remove();
                        $ps_container.show();
//                        $ps_title.show();
                        $ps_close.show();
                        $ps_overlay.show();
                        $(window).scrollTop(20);
                    }
                }).attr('src',item_source);
                
                
            }
        },'json');
    });
				
    /**
    * when hovering each one of the images, we show the button to navigate through them
    */
    $ps_container.live('mouseenter',function(){
        $('#ps_next_photo').show();
    }).live('mouseleave',function(){
        $('#ps_next_photo').hide();
    });
				
    /**
    * navigate through the images: the last one (the visible one) becomes the first one.
    * we also rotate 0 degrees the new visible picture 
    */
    $('#ps_next_photo').bind('click',function(){
        var $current = $ps_container.find('img:last');
        var r = Math.floor(Math.random()*41)-20;					
        var currentPositions = {
            marginLeft	: $current.css('margin-left'),
            marginTop	: $current.css('margin-top')
        };
        var $new_current = $current.prev();
					
        $current.animate({
            'marginLeft':'250px',
            'marginTop':'-385px'
        },250,function(){
            $(this).insertBefore($ps_container.find('img:first'))
            .css({
                '-moz-transform'    :'rotate('+r+'deg)',
                '-webkit-transform' :'rotate('+r+'deg)',
                '-o-transform'      :'rotate('+r+'deg)',
                'transform'         :'rotate('+r+'deg)'
            })
            .animate({
                'marginLeft':currentPositions.marginLeft,
                'marginTop' :currentPositions.marginTop
            },250,function(){
                $new_current.css({
                    '-moz-transform'	:'rotate(0deg)',
                    '-webkit-transform'	:'rotate(0deg)',
                    '-o-transform'	:'rotate(0deg)',
                    'transform'		:'rotate(0deg)'
                });
            });
        });
    });
				
    /**
    * close the images view, and go back to albums
    */
    $('#ps_close').bind('click',function(){
        $ps_container.hide();
        $ps_close.hide();
        $ps_overlay.fadeOut(400);
        $(window).scrollTop(currWindow);    //За сега местя прозореца нагоре и надолу, но може би е по-добре да отварям снимките в зависимост 
                                            //от положението на прозореца                                                
    });
				
    /**
    * resize and center the images
    */
    function resizeCenterImage($image){
        var theImage = new Image();
        theImage.src = $image.attr("src");
        var imgwidth = theImage.width;
        var imgheight = theImage.height;
					
        var containerwidth = 530;
        var containerheight = 400;
					
        if(imgwidth > containerwidth){
            var newwidth = containerwidth;
            var ratio = imgwidth / containerwidth;
            var newheight = imgheight / ratio;
            if(newheight > containerheight){
                var newnewheight = containerheight;
                var newratio = newheight/containerheight;
                var newnewwidth =newwidth/newratio;
                theImage.width = newnewwidth;
                theImage.height= newnewheight;
            }
            else{
                theImage.width = newwidth;
                theImage.height= newheight;
            }
        }
        else if(imgheight > containerheight){
            newheight = containerheight;
            ratio = imgheight / containerheight;
            newwidth = imgwidth / ratio;
            if(newwidth > containerwidth){
                newnewwidth = containerwidth;
                newratio = newwidth/containerwidth;
                newnewheight =newheight/newratio;
                theImage.height = newnewheight;
                theImage.width= newnewwidth;
            }
            else{
                theImage.width = newwidth;
                theImage.height= newheight;
            }
        }
        $image.css({
            'width'     :theImage.width,
            'height'	:theImage.height,
            'margin-top':-(theImage.height/2)-10+'px',
            'margin-left':-(theImage.width/2)-10+'px'	
        });
    }
//}

};                               //<-- function photoGallery

$.fn.calendarPicker = function(options) {
  
    // --------------------------  start default option values --------------------------
    if (!options.date) {
        options.date = new Date();
    }

    if (typeof(options.years) == "undefined")
        options.years=1;

    if (typeof(options.months) == "undefined")
        options.months=3;

    if (typeof(options.days) == "undefined")
        options.days=4;

    if (typeof(options.showDayArrows) == "undefined")
        options.showDayArrows=true;

    if (typeof(options.useWheel) == "undefined")
        options.useWheel=true;

    if (typeof(options.callbackDelay) == "undefined")
        options.callbackDelay=500;
  
    if (typeof(options.monthNames) == "undefined")
        options.monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    if (typeof(options.dayNames) == "undefined")
        options.dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    //------- my test
    if (typeof(options.showDays) == 'undefined')
        options.showDays = true;
  
    if(typeof(options.startYear) == 'undefined')
        options.startYear = false;
  
    if(typeof(options.startMonth) == 'undefined' || typeof(options.startYear) == 'undefined')
        options.startMonth = false;    
  
    // --------------------------  end default option values --------------------------

    var calendar = {
        currentDate: options.date
    };
    calendar.options = options;

    //build the calendar on the first element in the set of matched elements.
    var theDiv = this.eq(0);//$(this);
    theDiv.addClass("calBox");

    //empty the div
    theDiv.empty();

    var divYears = $("<div>").addClass("calYear");
    var divMonths = $("<div>").addClass("calMonth");
    var divDays = $("<div>").addClass("calDay");


    theDiv.append(divYears).append(divMonths).append(divDays);

    calendar.changeDate = function(date) {
        calendar.currentDate = date;

        var fillYears = function(date) {
            var year = date.getFullYear();                        //Взема годината от подадената дата
            var t = new Date();
            divYears.empty();                                     //Изпразваме div-а за да можем да изпишем годините наново
            var nc = options.years*2+1;                           //Определяме колко години ще се изписват
            //      var w = parseInt((theDiv.width()-4-(options.showDayArrows?12:0)-(nc)*4)/(nc-(options.showDayArrows?2:0)))+"px";
            var w = parseInt((theDiv.width()-((options.showDayArrows?16:0)+4+12)-(nc)*4)/nc)+"px";  //Изчисляваме щирината на един div за година в зависимост колко години ще се показват
            for (var i = year - options.years; i <= year + options.years; i++) {
                var d = new Date(date);
                d.setFullYear(i);
                var span = $("<span>").addClass("calElement").attr("millis", d.getTime()).html(i).css("width",w);
                if (d.getYear() == t.getYear())
                    span.addClass("today");
                if (d.getYear() == calendar.currentDate.getYear())
                    span.addClass("selected");
                // ---- my
                if (options.startYear){
                    if(d.getFullYear() < options.startYear || d.getFullYear() > t.getFullYear()){
                        span.addClass("nonSelectable");
//                $("div").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);
                    }
                }            
            divYears.append(span);
            }
    };

    var fillMonths = function(date) {
        var month = date.getMonth();
        var t = new Date();
        divMonths.empty();
        //      var oldday = date.getDay();
        var nc = options.months*2+1;
        var w = parseInt((theDiv.width()-4-8-(options.showDayArrows?12:0)-(nc)*4)/(nc-(options.showDayArrows?2:0)))+"px";

        for (var i = -options.months; i <= options.months; i++) {
            var d = new Date(date);
            var oldday = d.getDate();       //Взема деня от подадената дата
            d.setMonth(month + i);          //Установява месеца на ст-т, която трябва да се изпринти

            if (d.getDate() != oldday) {    //Проверка дали дните от подадения месец и новия зададен съвпадат
                d.setMonth(d.getMonth() - 1); 
                d.setDate(28);
            }
            var dYear = d.getFullYear(), dMonth = d.getMonth(), tYear = t.getFullYear(), tMonth = t.getMonth();
            var oYear = options.startYear, oMonth = options.startMonth;
        
            // --- my arrows
            var span = $("<span>").addClass("calElement").attr("millis", d.getTime());
        
            if( i == -options.months && options.showDayArrows ){
                span.addClass("prev").css("height", 16);
            } else if(i == options.months && options.showDayArrows){
                span.addClass("next").css("height", 16);
            } else {        
                span.attr("millis", d.getTime()).html(options.monthNames[d.getMonth()]).css("width",w);   
            }
        
            if (d.getYear() == t.getYear() && d.getMonth() == t.getMonth())
                span.addClass("today");
            if (d.getYear() == calendar.currentDate.getYear() && d.getMonth() == calendar.currentDate.getMonth())
                span.addClass("selected");
        
            // ----- my
            if (oYear){
                if(dYear < oYear || dYear > tYear){
                    span.addClass("nonSelectable");
                } else if(oMonth){
                    if((dYear == oYear && dMonth < oMonth) || (dYear == tYear && dMonth > tMonth)){
                        span.addClass("nonSelectable");
                    }
                }           
            }
        
            divMonths.append(span);        
        }
    };

    var fillDays = function(date) {
        var day = date.getDate();
        var t = new Date();
        divDays.empty();
        var nc = options.days*2+1;
        var w = parseInt((theDiv.width()-4-8-(options.showDayArrows?12:0)-(nc)*4)/(nc-(options.showDayArrows?2:0)))+"px";
        for (var i = -options.days; i <= options.days; i++) {
            var d = new Date(date);
            d.setDate(day + i)
        
        
            var span = $("<span>").addClass("calElement").attr("millis", d.getTime())
            if (i == -options.days && options.showDayArrows) {
                span.addClass("prev").css("height", 35);
            } else if (i == options.days && options.showDayArrows) {
                span.addClass("next").css("height", 35);
            } else {
                span.html("<span class=dayNumber>" + d.getDate() + "</span><br>" + options.dayNames[d.getDay()]).css("width",w);
                if (d.getYear() == t.getYear() && d.getMonth() == t.getMonth() && d.getDate() == t.getDate())
                    span.addClass("today");
                if (d.getYear() == calendar.currentDate.getYear() && d.getMonth() == calendar.currentDate.getMonth() && d.getDate() == calendar.currentDate.getDate())
                    span.addClass("selected");
            }
            divDays.append(span);

        }
    };

    var deferredCallBack = function() {
        if (typeof(options.callback) == "function") {
            if (calendar.timer)
                clearTimeout(calendar.timer);

            calendar.timer = setTimeout(function() {
                options.callback(calendar);
            }, options.callbackDelay);
        }
    };

    fillYears(date);
    fillMonths(date);
    if(options.showDays){
        fillDays(date);
    }
    deferredCallBack();

};

    theDiv.click(function(ev) {
        var el = $(ev.target);
        if (el.hasClass("calElement")) {
            if(el.hasClass("next")){
                el = $(".calMonth span.selected").next(".calElement");
            }else if(el.hasClass("prev")){
                el = $(".calMonth span.selected").prev(".calElement");
            }else{
                el = $(ev.target).closest(".calElement");
            }
            //        if(!el.hasClass("nonSelectable")){
            calendar.changeDate(new Date(parseInt(el.attr("millis"))));
        //        }
        }
    });

    //if mousewheel
    if ($.event.special.mousewheel && options.useWheel) {
        divYears.mousewheel(function(event, delta) {
            var d = new Date(calendar.currentDate.getTime());
            d.setFullYear(d.getFullYear() + delta);
            calendar.changeDate(d);
            return false;
        });
        divMonths.mousewheel(function(event, delta) {
            var d = new Date(calendar.currentDate.getTime());
            d.setMonth(d.getMonth() + delta);
            calendar.changeDate(d);
            return false;
        });
        divDays.mousewheel(function(event, delta) {
            var d = new Date(calendar.currentDate.getTime());
            d.setDate(d.getDate() + delta);
            calendar.changeDate(d);
            return false;
        });
    }

    calendar.changeDate(options.date);

    return calendar;
};                 //<-- function calendarPicker

$.fn.accessNews = function(settings){                           //<-- function accessNews Yahoo style
	
    var defaults = {            
        title: "TODAY NEWS:",                       // title for the display            
        subtitle: "Новини от последната седмица",   // subtitle for the display 
        date: "h2",                                 //pgk   date of the news
        slideBy: 4,                                 // number of slides to advance when paginating
        speed: "normal",                            // the speed for the pagination            
        slideShowInterval: 5000,                    // slideshow interval            
        slideShowDelay: 5000,                       // delay before slide show begins            
        theme: "default",                           // theme            
        continuousPaging : true,                    // allow the pagination to wrap continuously instead of stopping when the beginning or end is reached            
        contentTitle: "h3",                         // selector for the story title            
        contentSubTitle: "abbr",                    // selector for the story subtitle            
        contentDescription: "p",                    // selector for the story description            
        onLoad: null,                               // function to call when the slider first initializes            
        onComplete: null                            // function to call when the slider is done being created
    };

    return this.each(function(){
        settings = jQuery.extend(defaults, settings);
        var _this = jQuery(this);               //pgk   this is <ul> element
        var stories = _this.children();         //pgk   <li> elements
        var intervalId;
        var _storyIndictor;
        var _storyIndictors;

        var container = {
            _wrapper: '<div class="jqans-wrapper ' + settings.theme + '"></div>',
            _container: '<div class="jqans-container"></div>',
            _headline: jQuery('<div class="jqans-headline"></div>')
                .html(['<p><strong>', settings.title, '</strong> ', settings.subtitle, '</p>'].join("")),
            _content: jQuery('<div class="jqans-content"></div>'),
            _stories: '<div class="jqans-stories"></div>',
            _first: jQuery(stories[0]),
                init: function(){
                    if (settings.onLoad) {
                        settings.onLoad.call($(this));
                    }                    
                    _this.wrap(this._wrapper);              // wrap the ul with our div class and assigned theme                    
                    _this.before(this._container);          // our container where we show the image and news item
                    
                    var width = (stories.length * this._first.outerWidth(true));        // set the width of the container
                    _this.css("width", width);
                    if (settings.title.length){
                        this.append(this._headline);
                    }
                    this.append(this._content);                    
                    this.selector(width);                   // create the selector indicator
                    this.set(0);                            //pgk   call set method of container class
                    
                    pagination.init();                      // pagination setup
                    
                    slideshow.init();                       // slideshow setup

                    _this.wrap(this._stories);
                    if (settings.onComplete) {
                        settings.onComplete.call($(this));
                    }
                },
                selector: function(width){
                    var s = "";
                    for(var i = 1; i <= stories.length; i++){
                        s += "<li><div/></li>";
                    }
                    var o = jQuery("<div class=\"jqans-stories-selector\"></div>");
                    o.append("<ul>"+ s +"</ul>");
                    _storyIndictor = jQuery(o.find("ul"));
                    _storyIndictors = _storyIndictor.children();
                    o.css("width", width);
                    _this.before(o);
                },
                append: function(content){
                    this.get().append(content);
                },
                // returns the main container
                get: function(){
                    return _this.parents("div.jqans-wrapper").find('div.jqans-container');
                },
                set: function(position){
                    var container = this.get();
                    var story = jQuery(stories[position]);
                    var storyIndictor = jQuery(_storyIndictors[position]);
                    var _content = jQuery("div.jqans-content", container);
                    var img = jQuery('<img />');
                    var para = jQuery('<div></div>');
                    var title = jQuery(settings.contentTitle + " a", story).attr('title') || jQuery(settings.contentTitle, story).text();
                    if(jQuery(settings.date, story).text().length){
                        title = jQuery(settings.date, story).text() + ': ' + title;
                    }
                    img.attr('src', jQuery('img', story).attr('longdesc') || jQuery('img', story).attr('src'));
                    para.html("<h1>" + title + "</h1>" + "<p>" + jQuery(settings.contentDescription, story).html() + "</p>");
                    _content.empty();
                    _content.append(img);
                    _content.append(para);
                    stories.removeClass('selected');
                    story.addClass('selected');
                    _storyIndictors.removeClass('selected');
                    storyIndictor.addClass('selected');
                }
            };                  //<-- end container

        var pagination = {
            loaded: false,
            _animating: false,
            _totalPages: 0,
            _currentPage: 1,
            _storyWidth: 0,
            _slideByWidth: 0,
                init: function(){
                    if (stories.length > settings.slideBy) {
                        this._totalPages = Math.ceil(stories.length / settings.slideBy);
                        this._storyWidth = jQuery(stories[0]).outerWidth(true);
                        this._slideByWidth = this._storyWidth * settings.slideBy;
                        this.draw();
                        this.loaded = true;
                    }
                },
                draw: function(){
                    var _viewAll = jQuery('<div class="jqans-pagination"></div>')
                        .html(['<div class="jqans-pagination-count"><span class="jqans-pagination-count-start">1</span> - <span class="jqans-pagination-count-end">',
                            settings.slideBy, '</span> от <span class="jqans-pagination-count-total">',
                            stories.length, '</span> общо</div><div class="jqans-pagination-controls"><span class="jqans-pagination-controls-back"><a href="#" title="Back">&lt;&lt; Back</a></span><span class="jqans-pagination-controls-next"><a href="#" title="Next">Next &gt;&gt;</a></span></div>'].join(""));
                    _this.after(_viewAll);

                    var _next = jQuery(".jqans-pagination-controls-next > a", _viewAll);
                    var _back = jQuery(".jqans-pagination-controls-back > a", _viewAll);
                    _next.click(function(){
                        var page = pagination._currentPage + 1;
                        pagination.to(page);
                        return false;
                    });
                    _back.click(function(){
                        var page = pagination._currentPage - 1;
                        pagination.to(page);
                        return false;
                    });
                },
                to: function(page){
                    if(this._animating){
                            return;
                    }                        
                    this._animating = true;             // we're animating! 

                    var viewAll = _this.parent("div").next(".jqans-pagination");
                    var startAt = jQuery(".jqans-pagination-count-start", viewAll);
                    var endAt = jQuery(".jqans-pagination-count-end", viewAll);
                    if(page > this._totalPages){
                        page =  settings.continuousPaging ? 1 : this._totalPages;
                    }
                    if (page < 1) {
                        page =  settings.continuousPaging ? this._totalPages : 1;
                    }
                    var _startAt = (page * settings.slideBy) - settings.slideBy;
                    var _endAt = (page * settings.slideBy);
                    if (_endAt > stories.length) {
                        _endAt = stories.length;
                    }
                    var _left = parseInt(_this.css("left"));
                    var _offset = (page * this._slideByWidth) - this._slideByWidth; 
                    startAt.html(_startAt + 1);
                    endAt.html(_endAt);

                    _left = (_offset * -1);
                    _this.animate({
                        left: _left
                    }, settings.speed);
                    _storyIndictor.animate({
                        left: _left
                    }, settings.speed);
                  
                    container.set(_startAt);            // when paginating set the active story to the first story on the page
                    this._currentPage = page;                    
                    this._animating = false;            // no more animating :(
                }
            };                                          //<-- end pagination

        var slideshow = {
            init: function(){
                this.attach();
                this.off();
                intervalId = setTimeout(function(){
                    slideshow.on();
                }, settings.slideShowDelay);
            },
            on: function(){
                this.off();
                intervalId = setInterval(function(){
                    slideshow.slide();
                }, settings.slideShowInterval);
            },
            off: function(){
                clearInterval(intervalId);
            },
            slide: function(){                    
                var current = jQuery("li.selected", _this);         //currently selected story                    
                var next = current.next("li");                      // the next story                     
                var page = 0;                                       // page number
                if (!next.length) {
                    next = jQuery(stories[0]);
                    page = 1;
                }
                var storyIndex = stories.index(next);
                if (pagination.loaded) {
                    var storyMod = (storyIndex) % settings.slideBy;
                    if (storyMod === 0) {
                        page = (Math.ceil(storyIndex / settings.slideBy)) + 1;
                    }
                    if (page > 0) {
                        pagination.to(page);
                    }
                }
                container.set(storyIndex);
            },
            attach: function(){
                var that = jQuery(_this).parent("div.jqans-wrapper");
                that.hover(function(){                        
                    slideshow.off();                        // pause the slideshow on hover
                }, function (){                        
                    slideshow.on();                         // resume slideshow on mouseout
                });
            }
        };                                                  //<-- end slideshow

        //setup the container
        container.init();
        // append hover every to each element to update container content
        stories.hover(function(){                
            container.set(stories.index(this));             // set container contect to hovered li
        }, function(){
                // do nothing
        });
    });
};                     //<-- end accessNews Yahoo style

$.fn.msAccordion = function(options) {
    options = $.extend({
        currentDiv:'1',
        previousDiv:'',
        vertical: false,
        defaultid: $("#accordion-news div:first .title").attr("id"),     //pgk  old defaultid=0
        currentcounter:0,
        intervalid:0,
        autodelay:0,
        event:"click",
        alldivs_array:new Array()
    }, options);
    $(this).addClass("accordionWrapper").css({overflow:"hidden"});
    //alert(this);
    var elementid = $(this).attr("id");                                 //pgk this-> #accordion-news
    var allDivs = this.children();
    
    if(options.autodelay>0){
        $("#"+ elementid +" > div").bind("mouseenter", function(){pause();}).bind("mouseleave", function(){startPlay();});
    }
        //set ids
    allDivs.each(function(current) {
        var currentDiv = allDivs[current];
        var divID = $(currentDiv).find("div.title").attr("id");        
        var sTitleID = elementid+'_'+divID;
        var sContentID = sTitleID + '_content';
        
        $(currentDiv).find("div.title").attr("id", sTitleID);
        $(currentDiv).find("div.content").attr("id", sContentID);

        options.alldivs_array.push(sTitleID);
        $("#"+sTitleID).bind(options.event, function(){pause();openMe(sTitleID);});
    });    
    
    if(options.vertical) makeVertical();                //make vertical
    openMe(elementid+'_'+options.defaultid);            //elementid+"_msTitle_"+ open default tab on load, if not set, open first
    if(options.autodelay>0) startPlay();
    
    function openMe(id) {
        $("#"+id).addClass("active");                          
        options.currentcounter = id.split("_")[id.split("_").length-1];
        
        var sContentID = id+"_content";
        if($("#"+sContentID).css("display") == "none") {
            if(options.previousDiv!="") closeMe(options.previousDiv);          
            (options.vertical) ? $("#"+sContentID).slideDown("slow").addClass("active") : $("#"+sContentID).show("slow").addClass("active");

//            options.currentDiv = sContentID;
            options.previousDiv = options.currentDiv = sContentID;            
        }
    }
    
    function closeMe(div) {
        $("#"+div).removeClass("active");                                          
        $("#"+options.previousDiv.split("_content")[0]).removeClass(" active");  

        (options.vertical) ? $("#"+div).slideUp("slow") : $("#"+div).hide("slow");
    }
    
    function makeVertical() {
        $("#"+elementid +" > div").css({"display":"block", "float":"none", "clear":"both"});
        $("#"+elementid +" > div > div.title").css({"display":"block", "float":"none", "clear":"both"});
        $("#"+elementid +" > div > div.content").css({"clear":"both"});
    }
    
    function startPlay() {
        options.intervalid = window.setInterval(play, options.autodelay*1000);
    }
    
    function play() {
        var sTitleId = options.alldivs_array[options.currentcounter];
        openMe(sTitleId);
        options.currentcounter++;
        if(options.currentcounter==options.alldivs_array.length) options.currentcounter = 0;
    }
    
    function pause() {
        window.clearInterval(options.intervalid);
    }
};


$(document).ready(function() {

/********
 * SLIDESHOW
 */
    $('#slideshow').cycle({
        fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        speed: 'slow',
        timeout: 5000,
        pager: '#slider_nav',
        pagerAnchorBuilder: function(idx, slide) {
        // return sel string for existing anchor
            return '#slider_nav li:eq(' + (idx) + ') a';
        }
    });
/*******
 * TABS
 */
    $(".single-content").hide();
    $(".navi li:first").addClass("active");
    $(".single-content:first").show();
    $(".navi li").click(function(){
       $(".navi li").removeClass("active");
       $(this).addClass("active");
       $(".single-content").hide();
       var activeTab = $(this).find("a").attr("href");
       $(activeTab).fadeIn(500);
    });    
/**********
 * NEWS SLIDER
 */
    $('#newsslider').accessNews({
        title: 'КАРТИНГ ШУМЕН',
        subtitle:'',
        speed: 'slow',
        slideBy : 4,
        slideShowInterval: 20000,
        slideShowDelay: 20000
    });
/******
 * DATA TABLE
 */
    $('#dataGridBestShort').dataTable({
        "aoColumnDefs": [
            {"bVisible": false, "aTargets": [ 1 , 2 ]},
            {"fnRender": function ( oObj ) {
                return oObj.aData[0] +' '+ oObj.aData[1];
            },"aTargets": [ 0 ]}            
        ],
        "aaSorting": [[4,'asc']],
        'bAutoWidth': false,
        'bFilter': false,
        'bInfo': false,
        'bLengthChange': false,
        'bPaginate': false,
        'bSort': false
    });
    $('#dataGridCurr').dataTable({
        "aaSorting": [[4,'asc']],
        'bAutoWidth': false,
        'bFilter': false,
        'bInfo': false,
        'bLengthChange': false,
        'bPaginate': false,
        'bSort': false
    });
    
    $('#dataGridBest').dataTable({
        "aaSorting": [[4,'asc']],
        'bAutoWidth': false
    });
/*************
 * Accordion
 */
$("#accordion-news").msAccordion({
    vertical: 'true'
});

/*************
 * Validation engine
 */
$('#admin-form').validationEngine({scroll: false});
$('#admin-form').bind("jqv.form.validating", function(event){
    $("#jqError").removeClass('jqError').html("")
});
$('#admin-form').bind("jqv.form.result", function(event , errorFound){
    if(errorFound) $("#jqError").addClass('jqError').append("Попълнете задължителните полета");
});

//CalendarPicker

if($('div #tab-container').length){

    $("#calPicker").calendarPicker({
    monthNames:["Яну", "Фев", "Март", "Април", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Нов", "Дек"],
    dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    useWheel:true,
    callbackDelay:500,
    years:2,
    months:3,
//    days:3,
    showDayArrows:true,
    showDays:false,
    startYear: "2009",
    startMonth: "2",
//    date: myDate,
    callback:function(cal){
//        if($('div #tab-container').length){
        if(!$('div[class="calMonth"]>span[class*="selected"]').hasClass("nonSelectable") ) {
            $("#showMonth").text(this.monthNames[cal.currentDate.getMonth()] + ' ' + cal.currentDate.getFullYear());
            $.getJSON('resources/ajax_table_drivers.php', {month: cal.currentDate.getMonth()+1, year: cal.currentDate.getFullYear()}, function(data){
                $('#dataGrid').dataTable( {
                    "aoColumns":[
                        {"sTitle":"Име", "sClass":"right"},
                        {"sTitle":"Фамилия"},
                        {"sTitle":"Град"},
                        {"sTitle":"Дата"},
                        {"sTitle":"Време"} ],
                    "aaData": data.aaData,
//                    "bProcessing": true,
//                    "sAjaxSource": "../pages/rating/ajax_table_drivers.php?month="+cal.currentDate.getMonth()+ "&year="+cal.currentDate.getFullYear()
//                    "bRetrieve": true
                    "bDestroy":true,
                    "aaSorting": [[4,'asc']],
                    'bAutoWidth': false
                });
            });
        }
    }           // <-- callback function
    });         // <-- calendarPicker
}
    
//if($('#ps_albums').length){
//    loadPhotoGallery();
//}

if($('#ps_albums').length){
    $('#ps_albums').loadPhotoGallery({view:3});
}
$("#marquee").marquee({
    scrollSpeed: 20
});

});             // <-- document.ready
