PageTabs = (function() {
  var lis, reversedLis, back, next, count;
  function init() {
    back = $('back_button');
    next = $('next_button');
    if (back) {
      back.observe("click", goBack);
      next.observe("click", goNext);
      lis = $('tabs').select('li');
      count = 4;
      if (lis.length > 0 && lis.last().hasClassName('add_more_tab')) { 
        lis.pop();
        count = 3
      }
      reversedLis = lis.reverse(false);
    
      updateButtons();
      $('tabs').observe('click', changeTab);
    }
  }
  
  function changeTab(event) {
    var a = event.element().down('a') || event.element(),
        li = a.up('li')
    if (li.hasClassName('add_more_tab') || li.hasClassName('active'))
      return;
      
    document.location.href = a.href + "&first_index=" + firstTabIndex();
    event.stop();
  }
  
  function firstTabIndex() {
    var index = 0;
    lis.each(function(li) {
      if (li.visible())
        throw $break;
      index++;
    });
    return index;
  }
  
  function goBack() {
    if (back.hasClassName('button-back-disabled'))
      return;
    lis.each(function(li, index) {
      if (li.visible()) {
        lis[index - 1].show();
        if (index + count - 1 <= lis.length) {
          lis[index + count - 1].hide();
        }
        throw $break;
      }
    });
    updateButtons();
  }
  
  function goNext() {
    if (next.hasClassName('button-next-disabled'))
      return;
    reversedLis.each(function(li, index) {
      if (li.visible()) {
        reversedLis[index - 1].show();
        if (index + count - 1 <= lis.length) {
          reversedLis[index + count -1].hide();
        }
        throw $break;
      }
    });
    updateButtons();
  }
  
  function updateButtons() {
    if (lis.first().visible()) 
      back.removeClassName('button-back').addClassName('button-back-disabled');
    else
      back.addClassName('button-back').removeClassName('button-back-disabled')
      
    if (lis.last().visible()) 
      next.removeClassName('button-next').addClassName('button-next-disabled')
    else
      next.addClassName('button-next').removeClassName('button-next-disabled')
  }

  return {init:          init,
          firstTabIndex: firstTabIndex}
})();
  

Page =  (function() {
  var popup = new Popup(), newWidget = false, colorPicker = null;
  
  function init() {
    $$(".widgets li").each(function(element) {
      new Draggable(element, {revert: true, ghosting: true});
    })
    initDroppables();
    // initDraggables();
    if ($('layout-chooser'))
      $('layout-chooser').observe('click', setLayout);
    
    initTabs();
  }
  
  function initDroppables() {
    Droppables.drops.clear();
    $$(".droppable").each(function(element) {
      Droppables.add(element, {hoverclass: "hover", onDrop: drop});
    });
    $$(".draggable").each(function(element) {
      //console.log(element)
      //Droppables.add(element, {hoverclass: "hover", onDrop: drop});
    });
    
  }
  
  function initDraggables() {
    $$(".widget").each(function(element) {
      new Draggable(element, {revert: true, ghosting: true, handle: 'button-move'});
    })
  }
  
  function initTabs() {
    if ($('tabs')) {
      $('tabs').observe('click', editPage).observe('keydown', changePageName);
      if ($('edit_tab_name'))
        $('edit_tab_name').observe('blur', validatePageName);
    }
  }
  
  function editPage(event) {
    var element = event.element(), text = element.nextSiblings().first();
    if (element.tagName == 'A' && element.hasClassName('color2')) {
      element.hide();
      text.focus();
      event.stop();
    }
  }
  
  function changePageName(event) {
    var element = event.element(), a = element.previousSiblings().first();
    if (Event.KEY_ESC == event.keyCode) {
      element.blur();
      element.value = a.innerHTML;
      a.show();
      event.stop();
    }
    else if (Event.KEY_RETURN == event.keyCode) {
      element.blur();
    }
  }
  
  function validatePageName(event) {
    var element = $('edit_tab_name'), a = element.previousSiblings().first();
    element.blur();
    a.innerHTML = element.value;
    a.show();
    new Ajax.Request(paths.renamePage, {method: 'PUT', parameters: {authenticity_token: authenticity_token, 'page[title]': element.value}});
    event.stop();
  }
  
  function drop(element, drop) {
    if (element.tagName == 'LI') {
      var type     = element.id.split('_').last(),
          position = drop.up('table').select('td').indexOf(drop) + 1;

      drop.setStyle({backgroundImage: element.firstDescendant().getStyle('backgroundImage'), backgroundPosition: 'right -73px'});
      if (typeof lanceLaPopinAPoupou != "undefined")
        lanceLaPopinAPoupou(type, drop);
      else
	      new Ajax.Request(paths.newWidget, { parameters: {type: type, position: position, authenticity_token: authenticity_token},
                                            onSuccess: dropSuccess.curry(drop), 
                                            onFailure: dropFailed.curry(drop)});
                                          
    }
  }
  
  function dropSuccess(drop, response) {
    drop.innerHTML = response.responseText;
    newWidget = drop;
    setTimeout(function() {drop.down('a.button-edit').onclick()}, 100);
    initDroppables();
  }
  
  function dropFailed(drop, response) {
    drop.innerHTML = "Failed"
  }
  
  function editWidget(source) {
    if (typeof source == 'string') {
      source += "?first_index=" + PageTabs.firstTabIndex();
      popup.setAjaxContent(source, {method: 'GET'}, {cancel: cancelEditing });
    }
    else {
      popup.setContent(source, {cancel: cancelEditing });
    }
  }
  
  function cancelEditing() {
    if (newWidget) {
      var widget = newWidget.down('div'),
          id     = widget.id.split('_').last();
      removeWidget(widget, paths.newWidget + '/' + id, true);
    }
    newWidget = false;
  }
  
  function removeWidget(element, url, withoutConfirm) {
    var cell = element.up('td');
    
    if (withoutConfirm || confirm(i18n.are_you_sure)) {
      cell.addClassName('droppable').removeClassName('draggable');
      initDroppables();
      new Ajax.Request(url, { parameters: {authenticity_token: authenticity_token},
                              method: 'DELETE', 
                              onSuccess: function() {cell.innerHTML = ''; 
                                                     cell.style.backgroundImage = 'url(/images/zone_widget.png)';
                                                     cell.style.backgroundPosition = 'right top'}})
    }
  }
  
  function toggleLayoutPanel() {
    $('pages_select_layout').toggle();
    $('pages_modify_layout').toggle();
    $('pages_validate_layout').toggle();
    $('layout-chooser').toggle();
  }
  
  
  function setLayout(event) {
    event.stop();
    var element = event.element(), li = element.up('li');
    if (li && element.className != 'none') {      
      li.up('ul').select('li').invoke('removeClassName', 'selected')
      li.addClassName('selected');
      new Ajax.Request(paths.newLayout, { method: 'PUT',    
                                          parameters: {authenticity_token: authenticity_token, 
                                                       template:element.className},
                                          onComplete: initDroppables});
    }
  }
  
  function openColorPicker() {
    if (!colorPicker)
      colorPicker = new ColorPicker();
    colorPicker.show();
  }
  
  function validateColorPicker() {
    if (colorPicker)
      colorPicker.validate();
  }

  return {init:                 init,
          editWidget:           editWidget,
          toggleLayoutPanel:    toggleLayoutPanel,
          removeWidget:         removeWidget,
          openColorPicker:      openColorPicker,
          validateColorPicker:  validateColorPicker}
})();



ColorPicker = Class.create({
  initialize: function() {
    this.popup = new Popup('popin-colors-picker');
    this.popup.setContent($('color_picker_content'));
    this.popup.hide();
		this.selector = makeColorSelectors($('cp1_Hex'));
    $('color_select').observe('click', this.changeColorType.bind(this));
    $('restore_color').observe('click',this.restoreColor.bind(this));
  },
  
  show: function(){
    this.popup.show();
  },
  
  hide: function(){
    this.popup.hide();
  },
  
  validate:function() {
    var colors = [];
    $('color_select').select('li .color div').each(function(element) {
      colors.push(element.getStyle('backgroundColor').parseColor().replace('#', ''));
    })
    new Ajax.Request(paths.setColor, {parameters:{authenticity_token: authenticity_token, colors: colors.join(",")}});
  },
  
  changeColorType: function(event) {
    event.stop();
    $('color_select').select('li').invoke('removeClassName', 'selected');
    var element = event.element(), li = element.tagName == 'LI' ? element : element.up('li');
    li.addClassName('selected');		
    var colorElement = li.down('.color div');
    this.selector.setColorElement(colorElement);
  },
  
  restoreColor:function(event) {
    event.stop();
    var colors = defaultColors.split(',')
    $('color_select').select('li .color div').each(function(element, index) {
      element.style.background = '#' + colors[index];
      var selected = element.up("li.selected");
      if (selected) {
        this.selector.setColor(colors[index]);
      }
    }, this)
  }
});

AddressPicker = (function() {
  var widget; 
  function init(lat, lng) {
    widget = new Maptimize.AddressChooser.Widget(
      { street: 'map_widget_content',
        lat:    'map_widget_data_lat',
        lng:    'map_widget_data_lng',
        delay:   800,
        auto: false,
        onInitialized: function(widget) {
          // Add small map control (zoom and pan)
          widget.getMap().setUIToDefault();
          widget.getMap().disableScrollWheelZoom();
          var center  = [lat || 48.85771288591816, lng || 2.3486709594726562],
              zoom    = lat ? 15 : 12;
          //widget.getMap().setCenter(new GLatLng(center[0], center[1]), zoom);

          // Center map on selected address or on user location
          widget.initMap(zoom);

          // Focus street field
          $('map_widget_content').focus();
        }});
      widget.addEventListener('suggests:found', function(placemarks) {
        if (placemarks.length > 0) {
          $('submit_button').show();
        }
      });      
      $('map_widget_content').observe('keydown', keydown);
    }
    
    function keydown(event) {
      if (event.keyCode == 13) 
        event.stop();
    }
    
    function submit(element, event) {
      Moxity.UI.submitForm(element, event);
    }
    
    function show(element, lat, lng) {
      if (GBrowserIsCompatible()) {
        // Create a new google map
        var map = new GMap2($(element));

        // Center on the world
        map.setCenter(new GLatLng(lat, lng), 15);
        map.setUIToDefault();
        map.disableScrollWheelZoom();
        map.addOverlay(new GMarker(new GLatLng(lat, lng)));
      }
    }
    
    function showOnMap() {
      widget.updateMap();
    }
    
    return {init:      init,
            show:      show,
            showOnMap: showOnMap,
            submit:    submit};
})();

Page.init();
PageTabs.init();

Ticketing = {
  dateObserver:function(event) {
    var li = event.element().up('li');

    if (li) {
      var p = li.down('p');
  
      if (li.hasClassName("open")) {
        li.removeClassName("open");
        if (p)
          p.hide();
      } else {
        li.addClassName("open");
        if (p)
          p.show();
      }
      event.stop();
    }
  },
};

// Date expand/collapse code
document.whenReady(function() {
  var expand = $('expand');
  if (expand) {
    expand.observe('click', Ticketing.dateObserver);
  }  
});