﻿
jQuery.fn.cncaccordion = function(options) {
    var headerSelector = 'accordian-header';
    var expandBlock = 'ul-quickNavSub';

    // extract all the options
    if (options) {
        headerSelector = (options.header ? options.header : headerSelector);
        expandBlock = (options.block ? options.block : expandBlock);
    }

    var expanded = null;
    var selectedIndex = getCookie(headerSelector);

    $(this).find('.' + expandBlock).each(function(index) {
        if (selectedIndex) {
            if (index != selectedIndex) {
                $(this).hide();
            }
            else {
                expanded = $(this).parents('.' + headerSelector);
		expanded.id = 'open';
                $(this).parents('.' + headerSelector).addClass('sel');
		$(this).find('a').click(function(e) { e.stopPropagation() });
            }
        }
        else {
            $(this).hide();
        }
    });


    var hasCollapsed = false;

    $(this).children('.' + headerSelector).click(function() {
	
        if (expanded) {

	    $(expanded).find('.' + expandBlock).hide();
	    $(expanded).removeClass('sel');

	    if (this.id == 'open')
	    {
		this.id = '';
		hasCollapsed = true;
		expanded = null;
		selectedIndex = null;
	    }

//	    $('.' + expandBlock).each(function(index) {
//            	if (index == selectedIndex && $(this).is(':visible')) {
//			alert('found');
//			deleteCookie(headerSelector);
//                	expanded = null;
//			selectedIndex = null;
//			hasCollapsed = true;
//            }

//        });
        }

	if (!hasCollapsed)
	{

        expanded = this;
	this.id = 'open';

        $(this).find('.' + expandBlock).slideToggle('slow');
	$(this).find('.' + expandBlock);
        $(this).addClass('sel');

        $(this).find('.' + expandBlock + ' >li > a').click(function(e) { e.stopPropagation() });

        $('.' + expandBlock).each(function(index) {
            if ($(this).is(':visible')) {
                setCookie(headerSelector, index);
		selectedIndex = index;
            }
        });
	hasCollapsed = false;
	}
	else { hasCollapsed = !hasCollapsed; }
    });

    function getCookie(Name) {
        var re = new RegExp(Name + "=[^;]+", "i") //construct RE to search for target name/value pair
        if (document.cookie.match(re)) //if cookie found
            return document.cookie.match(re)[0].split("=")[1] //return its value
        return null
    }

    function setCookie(name, value) {
        document.cookie = name + "=" + value + "; path=/"
    }

    function deleteCookie(name) {
		if ( getCookie( name ) ) {
			 document.cookie = name + '=' +
			 '; path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT';
		}
    }

    return this;
};

