//Cookie support
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

(function($) { 
    $.fn.makeFAQ = function(options) {
        var defaults = {
            indexTitle: "Index",    // Change to whatever you want to be displayed
            faqHeader: ":header",   // default grabs any header element - h1,h2, etc...
            displayIndex: true      // Display Index
        };
        var options = $.extend(defaults, options);

        return this.each(function() {
            // load the parent object only once
            var $obj = $(this);

            // wrap parent in faqRoot div
            $obj.wrap("<div id='faqRoot'></div>");
            
            // Add index div
            if(options.displayIndex) {
                $obj.before("<div id='faqindex'><h2>" + options.indexTitle + "</h2><ul></ul></div>");
            };

            // Get header children using the obj ID
            var $faqEntries = $obj.children(options.faqHeader);
			// counting integer - ensures unique id names
			var i = 0;
            // enumerate through each entry and perform several tasks
            $faqEntries.each(function () {
                // load object only once
                var $entry = $(this);

                // Get entry name
                var entryName = $entry.text();
                // strip whitespaces and special characters
                var entryNameSafe = entryName.replace(/\W/g,"") + i;
				// Increment counter
                i++;

                // build index line for entry
                var itemHTML = "<li><a id='" + entryNameSafe.toString() + "Index' href='#" + entryNameSafe.toString() + "' >" + entryName + "</a></li>";
                // append the index line to the index
                $('#faqindex ul').append(itemHTML);

                // add click event for index entry
                if(options.displayIndex) {
                    $('#' + entryNameSafe.toString() + 'Index').click( function(){ 
                        // slide down the selected index before jumping to the bookmark    
                        $('#' + entryNameSafe.toString()).next('span').slideDown('fast');
                        // make sure it gets the faqopened class
                        $('#' + entryNameSafe.toString()).addClass('faqopened');
                     });
                };

                // add class to faq entry content
                $entry.next("div").addClass('faqcontent');

                // add title, name and id to entry
                $entry.attr({
                    title: "Click to expand/collapse",
                    name: entryNameSafe,
                    id: entryNameSafe                    
                    })
                    // add class
                    .addClass("faqclosed")
                    
                    // Add click event to entry
                    .click( function() {
                        $entry.next('div').slideToggle('fast');
                        $entry.toggleClass('faqopened');
                        })
                        // Collapse the span tag of the entry
                        .next('div').css({ 
                            display: "none"
                        });
            }); // end enumeration of each faq entry

        }); // end this each
    }; // end function
})(jQuery);

// Sidebar Toggle + Other bits and pieces
	$(document).ready( function() {
      $('a[rel*=facebox],a[href$=gif],a[href$=jpg]').facebox({      }) ;
	   $.facebox.settings.opacity = 0.5; 
	   $('a[href$=pdf]').addClass("pdf").click(function() {pageTracker._trackPageview(this.href)});
	  $('table.fancy tr:odd').addClass('odd');
	  $('a[href$=m4a]').click(function() {pageTracker._trackPageview(this.href)}); //Track podcasts dloads
	  $('.vid').click(function() {$test=$(this).find("div")[0].id;$test='#'+$test;jQuery.facebox({div: $test})});
	  $('.vid').hover(function() {
        	$(this).addClass('pretty-hover');
      	}, function() {
        	$(this).removeClass('pretty-hover');
      	});
	  
	/*  $('#faq').makeFAQ({
				indexTitle: "My Index",
				displayIndex: false,
				faqHeader: "h2"
			});*/


	$('.box-sidebar').each( function() {
		var widget_ID = $(this).attr('id');
		if ($.cookie(widget_ID) == 'open') {
			$(this).find('.totoggle').show();
			$(this).find('h3').addClass("toggle-close");
		} else {
			$(this).find('.totoggle').hide();
			$(this).find('h3').addClass("toggle-open");
		}
	});
	
	$(".box-clicker h3").click(function(){
										
	window.location = "/update";									
	});
	
	$(".box-sidebar h3").click(function(){
	
		if ($(this).next('div.totoggle').is(":hidden")) {
    	    $(this).next('div.totoggle').slideDown("slow");
    	    $(this).removeClass("toggle-open");
			$(this).addClass("toggle-close");
    	    $.cookie($(this).parent().parent().attr('id'), 'open',{ path: '/' });
			return false;
    	} else {
    		$(this).next('div.totoggle').slideUp("slow");
    		$(this).removeClass("toggle-close");
			$(this).addClass("toggle-open");
    	    $.cookie($(this).parent().parent().attr('id'), 'closed',{ path: '/' });
			return false;
    	}
      
     });
});