/*
    FAQ v1.1 Plugin
    
    A dynamic FAQ builder using the power of jQuery.

	Updated December 3rd, 2008 
		- Changed the span to a div - Symantically correct
		- Added an incrementor in case of a duplicate header name
		- Changed the regular expression to anything other than alphanumeric
		- Corrected the syntax to accept the faqHeader variable

    Example HTML Syntax:
    --------------------
    <div id="faq">
        <h2>Title 1</h2>
        <div>Some content</div>
        <h2>Title 2</h2>
        <div>Some content</div>
    </div>

    Example Script Syntax:
    --------------------
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.faq.js"></script>    
	<script type="text/javascript" >
	    $().ready(function() {
			$('#faq').makeFAQ({
				indexTitle: "My Index",
				displayIndex: true,
				faqHeader: "h2"
			});
	    });
	</script>

    Visit http://www.dscoduc.com for questions, comments, issues.
    Creative Commons Attribution-Share Alike
*/
(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
            singleItem: true
        };
        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 = 1;
            // 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;
                var entryNameSafe = i + "-faq";


                // 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 hidden anchor for jumping to
                var displayMode = "none";
                var displayCssClass = "faqclosed";
                var anchorID = i + "-faq";
                var anchorHTML = "<a name='" + i + "-faq'> </a>";
                $entry.prepend(anchorHTML);
                if (window.location.hash.substring(1) == anchorID) {
                    if (options.singleItem) {
                        if ($entry.attr('class') != 'faqclosed faqopened') {
                            $('#' + $obj.attr('id') + 'div').slideUp('fast');
                        }
                    }
                    displayMode = "visible";
                    displayCssClass = "faqclosed faqopened";
                }
                // Increment counter
                i++;

                // add title, name and id to entry
                $entry.attr({
                    title: "Click to expand/collapse",
                    name: entryNameSafe + "-title",
                    id: entryNameSafe + "-title"
                })
                // add class
                .addClass(displayCssClass)

                // Add click event to entry
                .click(function() {
                    // if singleItem set to true, hide any open content before displaying next
                    if (options.singleItem) {
                        if ($entry.attr('class') != 'faqclosed faqopened') {
                            $('#faq').closeAll();
                        }
                    }
                    $('#faq').openFAQ($entry.attr('id'));
                })
                // Collapse the div tag of the entry
                .next('div').css({
                    display: displayMode
                });
            }); // end enumeration of each faq entry

            // Following enables #3-faq anchor links within same page to open and jump to
            // Check for page anchor links add click to open if avail.
            var $faqLinks = $obj.children("div.faqcontent").children("a");
            // enumerate through each entry and perform several tasks
            $faqLinks.each(function() {
                // load object only once
                var $link = $(this);
                var patt = new RegExp("[^#]+$");
                var href = $link.attr('href');
                var hrefonly = href.split("#");
                var hashval = patt.exec(this.hash);

                // only add the click event if anchor is on current page
                if ((hrefonly[0] == "") || (hrefonly[0] == window.location.pathname)) {
                    $link.click(function() {
                        // close all faqs first
                        if (options.singleItem) {
                            $('#faq').closeAll();
                        }
                        $('#faq').openFAQ(hashval + '-title');
                    })
                } // end same page check
            }); // end faqcontent links each check

        }); // end this each
    }; // end makeFAQ function

    $.fn.closeAll = function() {
        var $obj = $(this);
        var $faqContent = $obj.children('h2');
        $faqContent.each(function() {
            // load object only once
            var $content = $(this);
            $content.next('div').slideUp('fast');
            $content.removeClass("faqopened");
        });
    }; //end close all

    $.fn.openAll = function() {
        var $obj = $(this);
        var $faqContent = $obj.children('h2');
        $faqContent.each(function() {
            // load object only once
            var $content = $(this);
            $content.next('div').slideDown('fast');
            $content.addClass("faqclosed faqopened");
        });
    }; //end close all

    $.fn.openFAQ = function(option) {
        $('#' + option).next('div').slideDown('fast');
        $('#' + option).addClass("faqclosed faqopened");
    }; // end open faq
})(jQuery);

$().ready(function() {
    $('#faq').makeFAQ({
        faqHeader: "h2",
        displayIndex: false,
        singleItem: true
    });
    
    // Get page name to use in the cookie
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);


    if(sPath.indexOf('/fr/') == -1)
    {
      var allColl = "Collapse All";
      var allExp = "Expand All";
    }else{
	var allColl = "Masquer les r&#233;ponses";
	var allExp = "Afficher les r&#233;ponses";
    }
    // Open the faq list if it was already opened before
    if ($.cookie(sPage) == 'open') {
        $('#faq').openAll();
        $('#faqexpand').html("<img src=\"/images/collapse-1.gif\"/> " + allColl);
        $.cookie(sPage, 'open');
    }else{
        $('#faqexpand').html("<img src=\"/images/expand-1.gif\"/> " + allExp);
    }
    $('#faqexpand').click(function() {
        // if link was expand then show and toggle text
        var currHTML = $('#faqexpand').html();
        if (currHTML.indexOf(getWord(allExp, 1)) > 0) {
            $('#faq').openAll();
            $('#faqexpand').html("<img src=\"/images/collapse-1.gif\"/> " + allColl);
            $.cookie(sPage, 'open');
        }
        // if link was collapse then hide and toggle text
        else {

            $('#faq').closeAll();
            $('#faq div').each(function(i) {
                //if (i==0) $(this).slideDown('fast'); //used to expand first option after collapse all
            });
            $('#faqexpand').html("<img src=\"/images/expand-1.gif\"/> " + allExp);
            $.cookie(sPage, 'closed');
        }
    });
});
function getWord(str,pos)
{
      var SplitString = str.split(" ");
      return SplitString[parseInt(pos)-1];
}
