setCookie = function(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

getCookie = function(name) {
  var results = document.cookie.match ( '(^|;) ?' + name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape( results[2] ));
  else
    return null;
}

deleteCookie = function(name) {
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = name += "=; expires=" + cookie_date.toGMTString();
}

setCookiePageName = function() {
    var pathname = location.pathname,
        start = pathname.lastIndexOf('/'),
        end = pathname.length;
        value = pathname.substring(start + 1, end);
    Tabs.cookiePageName = 'ACW' + value;
}

Tabs = {};
Tabs.cookiePageName;


Tabs.Init = function() {
    setCookiePageName();
    var cookieTab = getCookie(Tabs.cookiePageName),
        thisOne;
    if (cookieTab) {
        var tab = cookieTab.split('-'),
            tabIndex = tab[1],
            boxPanels = $('.boxPanel'),
            panelID = boxPanels[tabIndex-1].id || '100';       
        thisOne = "#" + panelID;
    } else {
	    thisOne = ':first';
	}
	$('.boxPanel').not(thisOne).hide();
}

Tabs.WriteNav = function() {
    var tabItems = $('.form .title').not('.form .list .title'),
        tab = 1;

    $('<ul class="boxNav"></ul>').insertBefore('.boxPanel:first').css({ 'margin-top': '25px' });
    $('.boxPanel').css({ 'margin-top': '0' });

    $.each(tabItems, function(indexInArray, valueOfElement) {
        $('.boxNav').append('<li><a href="#" id="tab-' + tab + '">' + $(valueOfElement).text() + '</a></li>');
        tab++;
    });
    
    var cookieTab = getCookie(Tabs.cookiePageName);
    
    if (cookieTab) {
        $("#" + cookieTab).parent().addClass('active');
    } else {
        $('.boxNav li:first').addClass('active');
    }
    $(tabItems).hide();
}

$(document).ready(function() {

    //Tab trigger hack. Force the block to be shown to avoid the floating tabs/hidden box problem.
    $('.boxPanel').css('display', 'block');

    Tabs.Init();
    Tabs.WriteNav();

    $('.boxNav a').click(function() {
        $(this).parent().addClass('active');
        $(this).parent().siblings().removeClass('active');
        var index = jQuery.inArray(this, jQuery(".boxNav li a"));
        var tabID = $(this).attr('id');
        setCookie(Tabs.cookiePageName, tabID);
        $('.boxPanel').hide();
        $('.boxPanel').eq(index).show();
        return false;
    });

});

