var tic = window.tic || {};
tic.initCityServicesPage = function() {
  $('div.city-services-page .collapsible-item .wrapper').hide();
  $('div.city-services-page .collapsible-item:first .wrapper').show();
  $('div.city-services-page .collapsible-item h2.title').wrapInner('<a href="#" />');
  $('div.city-services-page .collapsible-item h2.title a').click(function() {
    $(this).parent().parent().find('.wrapper').slideToggle();

    return false;
  });
}

tic.tabs = {};

tic.tabs.show = function(tab) {
    var id = $(tab).attr('rel');
    if (! document.getElementById(id))
        return;

    var el = $(document.getElementById(id));
    var tabs = el.parents('.tabs:first');
    if (! tabs.length)
        return;

    // hide all items
    tabs.find('.item').hide();

    // deactivate current tab
    tabs.find('.tabs-nav .active').removeClass('active');

    $(tab).parent().addClass('active');
    el.show();
}

tic.tabs.init = function() {
    $('div.tabs').each(function() {
        var items = $(this).find('div.item');
        var nav = $(document.createElement('ul'));
        nav.addClass('tabs-nav');

        var idPrefix = "i" + (new Date()).getTime().toString() + Math.random();

        var firstItem = null;
        var l = items.length;
        for (var i = 0; i < l; i++) {
            var title;
            if (title = $(items[i]).find('.title')) {
                var id = $(items[i]).id;
                if (!id) {
                    id = idPrefix + i;
                    $(items[i]).attr('id', id);
                }

                // create <a>
                var a = $(document.createElement('a'));
                a.attr('href', '');
                a.html('<span>' + title.text() + '</span>');
                a.attr('rel', id);
                a.click(function() {
                    tic.tabs.show(this);

                    return false;
                });

                // create <li>
                var li = $(document.createElement('li'));
                if (! firstItem) {
                    li.addClass('first');
                    firstItem = a;
                }
                li.append(a);
                nav.append(li);

                title.hide();
            }
        }

        $(this).prepend(nav);

        if (firstItem) {
            firstItem.trigger('click');
        }
    });
}

$(document).ready(function() {
    if ($('div.city-services-page').length) {
        tic.initCityServicesPage();
    }

    tic.tabs.init();

    if (jQuery.fancybox) {
      $('a.fancyimg').fancybox({type: 'image'});
    }
});
