var Cookie = {
  data: {},
  options: {expires: 1, domain: "", path: "", secure: false},

  init: function(options, data) {
    Cookie.options = Object.extend(Cookie.options, options || {});

    var payload = Cookie.retrieve();
    if(payload) {
      Cookie.data = payload.evalJSON();
    }
    else {
      Cookie.data = data || {};
    }
    Cookie.store();
  },
  
  getData: function(key) {
    return Cookie.data[key];
  },
  setData: function(key, value) {
    Cookie.data[key] = value;
    Cookie.store();
  },
  removeData: function(key) {
    delete Cookie.data[key];
    Cookie.store();
  },
  retrieve: function() {
    var start = document.cookie.indexOf(Cookie.options.name + "=");

    if(start == -1) {
      return null;
    }
    if(Cookie.options.name != document.cookie.substr(start, Cookie.options.name.length)) {
      return null;
    }

    var len = start + Cookie.options.name.length + 1;   
    var end = document.cookie.indexOf(';', len);

    if(end == -1) {
      end = document.cookie.length;
    } 
    return unescape(document.cookie.substring(len, end));
  },
  store: function() {
    var expires = '';

    if (Cookie.options.expires) {
      var today = new Date();
      expires = Cookie.options.expires * 86400000;
      expires = ';expires=' + new Date(today.getTime() + expires);
    }

    document.cookie = Cookie.options.name + '=' + escape(Object.toJSON(Cookie.data)) + Cookie.getOptions() + expires;
  },
  erase: function() {
    document.cookie = Cookie.options.name + '=' + Cookie.getOptions() + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
  },
  getOptions: function() {
    return (Cookie.options.path ? ';path=' + Cookie.options.path : '') + (Cookie.options.domain ? ';domain=' + Cookie.options.domain : '') + (Cookie.options.secure ? ';secure' : '');      
  }
};


function certifyRightsToPhoto(checkboxId, fileId, msg) {
	var checkbox = $(checkboxId);
	var filefield = $(fileId);
	if(!checkbox.checked && filefield.value.length != 0) {
		alert(msg);
		return false;
	} else {
		return true;
	}
}

function certifyCGV(msg) {
	if ($('certify_cgv').checked) {
		return true;
	} else {
		alert(msg);
	}
}

function showEventsDate(element, toSelectId) {
  element.up('table').select('td').invoke('removeClassName', 'today today-counter');
  element.addClassName("today today-counter");
	$$('div.date').invoke('hide');
	$(toSelectId).show();
}

function updateCurrentModalDialogSize() {
  UI.defaultWM.getFocusedWindow().adapt();
}

function closeCurrentModalDialog() {
  UI.defaultWM.getFocusedWindow().destroy();
}

Moxity = {};

Moxity.UI = (function() {
  var beginDate = null, date = null;
  
  function registerCategoryCheckboxes() {
    document.observe('dom:loaded', function()  {
     $('filters-thematiques').observe('click', function(event) {
       var themeForm =  $('themes'),
           params = themeForm.serialize()+"&authenticity_token="+authenticity_token;
       if (beginDate) 
         date += "&begin_date=" + beginDate;
       if (beginDate) 
        params += "&date=" + date;
        
       new Ajax.Request(themeForm.action, {parameters: params, method: 'GET'})
      })
    })
  }
  
  function registerAgendasCheckboxes() {
    document.observe('dom:loaded', function()  {
     $('filters-agendas').observe('click', function(event) {
       var agendasForm =  $('agendas');
       new Ajax.Request(agendasForm.action, {parameters: agendasForm.serialize()+"&authenticity_token="+authenticity_token,
                                           method: 'GET'})
      })
    })
  }

  function registerMyAgendaCheckboxes() {
    document.observe('dom:loaded', function()  {
     $('filters').observe('click', function(event) {
       var agendasForm =  $('agendas');
       new Ajax.Request(agendasForm.action, {parameters: agendasForm.serialize()+"&authenticity_token="+authenticity_token,
                                           method: 'GET'})
      })
    })
  }
  
  function setDate(begin, current) {
    beginDate = begin;
    date = current;
  }

  function changeCurrentDate(url) {
    var selected = currentTab(), parameters;

    if (selected == 'search-thematiques') 
      parameters = $('themes').serialize();
	else if (selected == 'search-agendas')
	  parameters = $('agendas').serialize();
    else if (selected == 'search-tags') {
      var selectedTag = $$("#filters-tags a.selected").first();
      parameters = selectedTag ? "tag=" + selectedTag.id.gsub(/^tag\-/, "") : null;
    }
    if (Map.isFullSize())
      parameters+="&full_timeline=" + Map.isFullSize();
    new Ajax.Request(url, {method: 'GET', parameters: parameters});
  }
  
  function currentTab() {
    var selected = $$("ul#select_filters li.selected").first();
    return selected.id;
  }

  function submitForm(element, event) {
    var form = element.up('form'), loader = element.next();
    if (loader) {
      loader.show();
      element.hide();
    }

    if (!form.onsubmit || form.onsubmit()) {
      form.submit();
    }
    else {
      if (form.onsubmit) {
        if (loader) {
          loader.hide();
          element.show();
        }
      }
      event.stop();
    }
  }

  function displayFlash() {
    var flash = $$('.flash');
    if (! flash.empty()) {
      var content = $("flash_window"),
          message = flash.inject('', function(result, item) {result += item.innerHTML + '<br/>'; return result});

      $('flash_window_content').update(message);
      new Popup().setContent(content);
    }
  } 
  
  
  function changeNbPlace(other, confirmMessage, url) {
    if (confirm(confirmMessage)) {
      new Ajax.Request(url, {asynchronous:true, evalScripts:true, method:'put', parameters:'authenticity_token=' + authenticity_token}); 
    }
    else {
      $(other).checked = true;
    }
  }

  function affectToDates(other, confirmMessage, url) {
	if (confirm(confirmMessage)) {
		new Ajax.Request(url, {asynchronous:true, evalScripts:true, method:'put', parameters:'authenticity_token=' + authenticity_token});
	} else {
		$(other).checked = true;
	}
  }

	function submitPublication(element) {
		$('event-status').down('div').update('<img src="/images/widgetLoader.gif" style="width:145px;height:18px"/>');
		$(element).up('form').onsubmit();
	}
	
	function displayVideo(video) {
	  var popup = new Popup();
	  popup.setContent($(video));
	  
	  var offset = document.viewport.getScrollOffset();
	  popup.element.style.top = 100 + offset[1] + 'px';
	}
  
  return {registerCategoryCheckboxes: registerCategoryCheckboxes,
	        registerAgendasCheckboxes:  registerAgendasCheckboxes,
		     	registerMyAgendaCheckboxes: registerMyAgendaCheckboxes,
          changeCurrentDate:          changeCurrentDate,
          setDate:                    setDate,
          submitForm:                 submitForm,
          displayVideo:               displayVideo,
          displayFlash:               displayFlash,
          changeNbPlace:              changeNbPlace,
		  affectToDates:              affectToDates,
		  submitPublication:          submitPublication}
}());

Abuse = {
  openPopup:function() {
    var popup = new Popup();
    popup.setContent($('abuse'));
  },

	submit:function(element, event) {
		var email   = $('email').value.strip(),
			  content = $('message').value.strip(),
				error   = false;
		
		if (email.empty()) {
			$('email-label').addClassName('error');
			error = true;
		}
		else {
			$('email-label').removeClassName('error');
		}
		
		if (content.empty()) {
			$('content-label').addClassName('error');
			error = true;
		}
		else {
			$('content-label').removeClassName('error');
		}

		if (error) 
			event.stop();
		else
			Moxity.UI.submitForm(element, event);
	}
}

Event.addBehavior.reassignAfterAjax = true;
Event.addBehavior({
  'div.ajax_pagination a': Remote.Link
});
  
document.observe('dom:loaded', function() {
  Moxity.UI.displayFlash();
})


