(function ($) {
    $.fn.hookWidgetTabs = function () {
        return this.each(function() {
				var $$ = $(this);
				$$.tabs({
			            selected : 0,
			            selectedClass : 'selected', 
			            hideClass : 'hide', 
			            fx: { 
			                opacity : 'toggle', 
			                duration : 'fast' 
			            } 
					});
				});
    };


	jQuery.fn.extend({
		syncLoad: function( url, params, callback ) {
			if ( jQuery.isFunction( url ) )
				return this.bind("syncLoad", url);

			var off = url.indexOf(" ");
			if ( off >= 0 ) {
				var selector = url.slice(off, url.length);
				url = url.slice(0, off);
			}

			callback = callback || function(){};

			// Default to a GET request
			var type = "GET";

			// If the second parameter was provided
			if ( params )
				// If it's a function
				if ( jQuery.isFunction( params ) ) {
					// We assume that it's the callback
					callback = params;
					params = null;

				// Otherwise, build a param string
				} else {
					params = jQuery.param( params );
					type = "POST";
				}

			var self = this;

			// Request the remote document
			jQuery.ajax({
				url: url,
			   	cache: false,
		  		async: false,
				type: type,
				dataType: "html",
				data: params,
				complete: function(res, status){
					// If successful, inject the HTML into all the matched elements
					if ( status == "success" || status == "notmodified" )
						// See if a selector was specified
						self.html( selector ?
							// Create a dummy div to hold the results
							jQuery("<div/>")
								// inject the contents of the document in, removing the scripts
								// to avoid any 'Permission Denied' errors in IE
								.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

								// Locate the specified elements
								.find(selector) :

							// If not, just inject the full result
							res.responseText );

					self.each( callback, [res.responseText, status, res] );
				}
			});
			return this;
		}
	});


    $.fn.setControls = function () {
        return this.each(function () {
            var $$ = $(this);
            var dirs = [];
            var direction = '';

            if ($$.is('.vertical')) {
                dirs = ['up', 'down'];
                direction = 'vertical';
            } else {
                dirs = ['left', 'right'];
                direction = 'horizontal';
            }

            var pager = $$.parents('div.widget:first').find('.paged').pageSlider({
                easing : 'easeInOutCirc',
                direction : direction
            });

            var nav = '<ul><li><img class="' + dirs[0] + '" src="http://beta.vita.it/images/' + dirs[0] + '.gif" /></li><li><img class="' + dirs[1] + '" src="http://beta.vita.it/images/' + dirs[1] + '.gif" /></li></ul>';
            $$.append(nav)
                .find('img')
                .css('cursor', 'pointer')
                .click(function () {
                    if (this.className == dirs[0]) {
                        pager.trigger('back');
                    } else {
                        pager.trigger('forward');
                    }
                });
        });
    };

    $.fn.pageSlider = function (options) {
        var defaults = {
            pages : '> div',
            direction : 'vertical',
            duration : 500,
            easing : 'swing'
        };

        var settings = $.extend({}, defaults, options);
        var vert = settings.direction.toLowerCase().substr(0, 1) == 'v';

        function back(event) {
            move(event.data.wrapper, false);
        }

        function forward(event) {
            move(event.data.wrapper, true);
        }

        function move(wrapper, forward) {
            // prevent multi clicking and problems with animation
            if (!wrapper.is(':animated')) {
                var p = (vert ? 'top' : 'left');
                var steps = wrapper.data('steps');

                var next = wrapper.data('current');

                if (forward) {
                    next++;

                    if (next >= steps.length) {
                        next = 0;
                    }
                } else {
                    next--;
                    if (next < 0) {
                        next = steps.length - 1;
                    }
                }

                wrapper.data('current', next);
                animate(wrapper);
            }
        }

        function animate(wrapper) {
            var i = wrapper.data('current');
            var steps = wrapper.data('steps');
            var prop = vert ? {
                'top' : steps[i]
            } : {
                'left' : steps[i]
            };

            var r = wrapper.animate(prop, {
                duration: settings.duration,
                easing : settings.easing
            });
        }

        return this.each(function () {
            var $$ = $(this).css('overflow', 'hidden');
            var pages = $$.find(settings.pages || '> div');

            var wrapper = $(document.createElement('div'));
            wrapper.css('position', 'relative');
            wrapper = pages.wrapAll(wrapper).parent();

            if (vert == false) { // i.e. horizontal
                // allow them to stack against eachother
                pages.css({
                    'float' : 'left',
                    'marginRight' : $$.css('marginRight'),
                    'paddingRight' : $$.css('paddingRight'),
                    'width' : $$.width()
                });
                wrapper.css('width', this.offsetWidth * pages.length);
                var vertWrapper = wrapper.wrapAll('<div />').parent();
                vertWrapper.css('overflow', 'hidden');
            }

            var steps = [];
            var idToStep = {};
            pages.each(function () {
                steps.push((vert ? this.offsetTop : this.offsetLeft) * -1);
                if (this.id) {
                    idToStep[this.id] = steps.length-1;
                }
            });

            wrapper.data('steps', steps);
            wrapper.data('current', 0);
            $$.bind('back', { wrapper : wrapper }, back);
            $$.bind('forward', { wrapper : wrapper }, forward);

            if ($$.is('.auto')) {
                return true;
            }
        });
    };
    
    $.fn.newsScroll = function (options) {
        var defaults = {
            target : '> div',
            startDelay : 2000,
            duration : 4000
        };
        
        var settings = $.extend({}, defaults, options);
        return this.each(function () {
            var $$ = $(this).css({'overflow' : 'hidden', 'position' : 'relative' });
            var wrapper = $$.find(settings.target).wrapAll('<div />').parent();
            wrapper.css('position', 'relative');
            wrapper.hover(function () {
                clearTimeout(timer);
                $(this).stop();
            }, animate).addClass('scrollWrapper');
            
            var reset = $$.height();
            var spacer = $('<div />');
            spacer.css({
                height : reset
            }).appendTo(wrapper).clone().prependTo(wrapper);

            var targets = wrapper.find(settings.target);
            var total = targets.length;
            var current = 1;
            var timer = null;
            var isScrolling = false;

            $$.scrollTo(targets.eq(current), 0);
            
            setTimeout(animate, settings.startDelay);
            
            function animate() {
                if (isScrolling) return;
                
                var t = targets.eq(current);
                isScrolling = true;
                $$.scrollTo(t, 500, {
                    easing : 'linear',
                    axis : 'y',
                    onAfter : function () {
						var waittime = 2000;
                        if (current < total-1) {
                            current++;
							waittime = 5000;
                        } else {
                            $$.scrollTo(0, 0);
                            current = 1;
							waittime = 5;
                        }
                        isScrolling = false;
                        timer = setTimeout(animate, waittime); // infinite loop
                    }
                });
            }
        });
    };
})(jQuery);

function hookCheckAll(check) {
	check.change(function() {
		$('.checkall').each( function() {
			this.checked = !this.checked;
		});
		return false;
	})
}

function enableDraggableWidgets() {
    if ($.fn.sortable) {
        // only apply to the home page
        $('#home #content').sortable({
            placeholder: 'widgetHolder',
            items: '> .widget:not(.fixed)',
            handle: '> h3:first, > ul.navigation',
            cursor: 'move',
            scroll: true,
            tolerance: 'pointer',
            update: function () {
                var order = $('#content > .widget').map(function () {
                    return this.id;
                }).get().join(',');

                // should be sent via Ajax request to handle server side ordering
            }
        }).find('.widget > h3,.widget > ul.navigation').css('cursor', 'move');
    }
}


$(function () {
    if ($.fn.accordion) $('.accordion').accordion({
        header: 'H4'
        // event: 'click'
    }).find('h4').css('cursor', 'pointer');
    
    $('div.autoscroll').newsScroll({target : '> div', duration : 2000});
        
    // vertical scrollers
    $('div.widgetControls').setControls();

    $('#logo').click(function () {
        var homeLink = $('#navHome a').attr('href');
        window.location = homeLink;
    }).css('cursor', 'pointer');

    $('#navigation li, #heroNavigation li').hover(function () {
        $(this).addClass('over');
    }, function () {
        $(this).removeClass('over');
    });

    if ($.fn.tabs) {
        $('ul.tabs').tabs({
            selected : 0,
            selectedClass : 'selected', 
            hideClass : 'hide', 
            fx: { 
                opacity : 'toggle', 
                duration : 'fast' 
            } 
        }).filter('#heroNavigationList').tabs( "rotate", 3000);
    }

    enableDraggableWidgets();

    var cp = $('.controlPanel');

    // apparently we can't even toggle it back on the toggleSlide complete :-(
    // if ($.browser.msie && $.browser.version < 7) {
    //     // IE6 seems to put tables above the animation - so we'll just hide it.
    //     $('#controlPanel table').hide();
    // }


    // must go after limit code otherwise numbers come out wrong
    if ($.fn.hint) $('input.hint, textarea.hint').hint();

    $('#miniProfile a.toggleControlPanel').click(function () {
		// Added by NP - 2008-06-24
		// $('#cpContent').load('/user/notlogged');
        cp.slideToggle(500);
        return false;
    });

	 // $.ajaxSetup({
	 //   	cache: false,
	 //  		async: false
	 // });
});

