/**
 * @author daco de la bretoniere
 */





/**
 * iSelect functions
 */

ComicHouse.Iselect_functions = Class.create ({
	
	show: function(){
		
		$('iselectfunctions').show(); $('art').hide();
		$$('#iselectfunctions > div').invoke('hide');
		this.node.show();
	}

});



ComicHouse.Iselect_show = Class.create (ComicHouse.Iselect_functions, {
	initialize: function() {
		document.observe('dom:loaded', this._init.bind(this));
	},
	
	_init: function(){
		if (!$('iselectfunctions')) {
			return;
		}

		this.node = $('iselect_show_txt');

	}
	
});
ComicHouse.iselect_show = new ComicHouse.Iselect_show();



ComicHouse.Iselect_write = Class.create (ComicHouse.Iselect_functions, {
	initialize: function() {
		document.observe('dom:loaded', this._init.bind(this));
	},
	
	_init: function(){
		if (!$('iselectfunctions')) {
			return;
		}
		
		this.contextpath = $('main').readAttribute('contextpath');
		this.node = $('iselect_write_txt');
		this.nameinput = $('write_iselectname');
		this.nameinput.observe('keypress', function(evt){
			if (evt.keyCode == Event.KEY_RETURN) {
				this.savebutton.fire('custom:click');		
			}
		}.bind(this));
		this.descriptioninput = $('write_iselectdescription');
		this.savebutton = $('iselect_write');
		this.savebutton.observe('click', this._write.bind(this));
		this.savebutton.observe('custom:click', this._write.bind(this));
	},
	
	_write: function(){
		
		var button = new ComicHouse.modalDialogButton();
		button.create('ok', function(){});
		
		if (!this.nameinput.value.match(/^[a-z,A-Z,0-9,_]{1,20}$/)) {
			
			ComicHouse.modalDialog(ComicHouse.localizedText.iselect_only_chars_and_numbers, [button]);
			return;
			
		}

		var write = function() {
			
			new Ajax.Request('/' + this.contextpath + 'iselect/write',
					
					{
						method:'post',
						parameters:{name:this.nameinput.value, description:this.descriptioninput.value},
						onComplete:function(transport){
							
							var response = transport.responseText.evalJSON();
							
							if (typeof response.error == 'string') {
								ComicHouse.modalDialog(ComicHouse.localizedText.iselect_name_already_taken, [button]); 						
							} else {
								ComicHouse.modalDialog(ComicHouse.localizedText.iselect_selection_is_saved, [button]);
							}
							
						}
					}
				
				);		
		}.bind(this);
		
			
		write();
			

	}
	
});
ComicHouse.iselect_write = new ComicHouse.Iselect_write();



ComicHouse.Iselect_send = Class.create (ComicHouse.Iselect_functions, {
	initialize: function() {
		document.observe('dom:loaded', this._init.bind(this));
	},
	
	_init: function(){
		if (!$('iselectfunctions')) {
			return;
		}
		this.contextpath = $('main').readAttribute('contextpath');
		this.node = $('iselect_send_txt');
		 
		this.iselect_email_name = $('iselect_send_name');
		this.iselect_email_description = $('iselect_send_description');
		
		this.iselect_email_sender = $('iselect_email_sender');
		this.iselect_email_recipient = $('iselect_email_recipient');
		this.iselect_email_recipient.observe('keypress', function(evt){
			if (evt.keyCode == Event.KEY_RETURN) {
				this.savebutton.fire('custom:click');		
			}
		}.bind(this));
		this.savebutton = $('iselect_send_email');
		this.savebutton.observe('click', this._send.bind(this));
		this.savebutton.observe('custom:click', this._send.bind(this));
	},
	
	show: function(){
		$('iselectfunctions').show(); $('art').hide();
		$$('#iselectfunctions > div').invoke('hide');
		this._showIfPossible();
	},

	_setNameAndDescription: function(response){
		this.iselect_email_name.update(response.name);
		this.iselect_email_description.update(response.description);	
	},
	
	_show: function(){
		this.node.show();	
	},
	
	_showIfPossible: function(){
		
		var self = this;
		
		// is this session saved?
		new Ajax.Request('/' + this.contextpath + 'iselect/getnameanddescription',
				
				{
					method:'post',
					parameters:{from:this.iselect_email_sender.value, to:this.iselect_email_recipient.value},
					onComplete:function(transport){
						
						var response = transport.responseText.evalJSON();
						
						if (typeof response.error == 'string') {
							
							var button = new ComicHouse.modalDialogButton();
							button.create('ok', function(){});
							ComicHouse.modalDialog(ComicHouse.localizedText.iselect_save_selection_before_sending, [button]);
							ComicHouse.iselect_write.show();			
						} else {
							
							self._setNameAndDescription(response);
							self._show();
							
						}
						
					}
				}
			
		);
		
	},
	
	_sendIfPossible: function(){
	
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (this.iselect_email_sender.value.match(filter) && this.iselect_email_recipient.value.match(filter)) {
			
			return true;
			
		} else {
			
			var button = new ComicHouse.modalDialogButton();
			button.create('ok', function(){});
			ComicHouse.modalDialog(ComicHouse.localizedText.iselect_enter_valid_email_address, [button]);
			
			return false;
			
		}
		
	},
	
	_send: function(){
		
		if(this._sendIfPossible()) {
		
			new Ajax.Request('/' + this.contextpath + 'iselect/emailiselection',
					
					{
						method:'post',
						parameters:{from:this.iselect_email_sender.value, to:this.iselect_email_recipient.value},
						onComplete:function(){

							var button = new ComicHouse.modalDialogButton();
							button.create('ok', function(){});
							ComicHouse.modalDialog(ComicHouse.localizedText.iselect_mail_send, [button]);
							
						}
					}
				
			);
		
		} else {
			
		}
		
	}
	
});
ComicHouse.iselect_send = new ComicHouse.Iselect_send();


ComicHouse.Iselect_read = Class.create (ComicHouse.Iselect_functions, {
	initialize: function() {
		document.observe('dom:loaded', this._init.bind(this));
	},
	
	_init: function(){
		if (!$('iselectfunctions')) {
			return;
		}
		this.contextpath = $('main').readAttribute('contextpath');
		this.locale = $('main').readAttribute('locale');
		this.node = $('iselect_read_txt');
		this.nameinput = $('read_iselectname');

		this.savebutton = $('iselect_read');
		
		this.nameinput.observe('keypress', function(evt){
			if (evt.keyCode == Event.KEY_RETURN) {
				this.savebutton.fire('custom:click');		
			}
		}.bind(this));

		this.savebutton.observe('click', this._read.bind(this));
		this.savebutton.observe('custom:click', this._read.bind(this));
		
	},
	
	_read: function(){
		
		var self = this;

		new Ajax.Request('/' + this.contextpath + 'iselect/read/' + this.nameinput.value,
		
			{
				method:'get',
				onComplete:function(transport){

					var response = transport.responseText.evalJSON();
					
					if (typeof response.error != 'string') {
						// use permalink feature
						location.href = '/' + self.contextpath + self.locale + '/iselect/' + self.nameinput.value + '.html';
					} else {
						
						var button = new ComicHouse.modalDialogButton();
						button.create('ok', function(){});
						ComicHouse.modalDialog(ComicHouse.localizedText.iselect_name_does_not_exist, [button]);
					
					}
					
				}
			}
		
		);		

	}
	
});
ComicHouse.iselect_read = new ComicHouse.Iselect_read();


ComicHouse.Iselect_clear = Class.create (ComicHouse.Iselect_functions, {
	initialize: function() {
		document.observe('dom:loaded', this._init.bind(this));
	},
	
	_init: function(){
		if (!$('iselectfunctions')) {
			return;
		}
		this.contextpath = $('main').readAttribute('contextpath');
		this.locale = $('main').readAttribute('locale');
		this.node = $('iselect_clear_txt');
		
	},

	_clear: function(){

		var locale = $('main').readAttribute('locale');
		new Effect.Shrink($('imageCol'));
		new Ajax.Request('/' + this.contextpath + 'iselect/clear', {onComplete:function(){location.href = locale + '/' + this.contextpath + 'iselect/show';}.bind(this)});
	
	},	
	
	show: function(){
		this._showDialog();	
	},
	
	_showDialog: function () {
		
		var yes_button = new ComicHouse.modalDialogButton();
		yes_button.create('yes', this._clear.bind(this));
		
		var no_button = new ComicHouse.modalDialogButton();
		no_button.create('no', function(){});
		
		ComicHouse.modalDialog(ComicHouse.localizedText.iselect_are_you_sure, [yes_button, no_button]);	
		
	}
	
});
ComicHouse.iselect_clear = new ComicHouse.Iselect_clear();


ComicHouse.Iselect_help = Class.create (ComicHouse.Iselect_functions, {
	initialize: function() {
		document.observe('dom:loaded', this._init.bind(this));
	},
	
	_init: function(){
		if (!$('iselectfunctions')) {
			return;
		}
		this.node = $('iselect_help_txt');
		
	}
	
});
ComicHouse.iselect_help = new ComicHouse.Iselect_help();

/**
 * / iSelect functions
 */
 
ComicHouse.IselectRow = Class.create ({
	
	initialize: function(domNode, iselect) {

		this.contextpath = $('main').readAttribute('contextpath');
		this.domNode = domNode;
		this.iselect = iselect;
		this.artworkid = this.domNode.readAttribute('artworkid');

		this.iselectStateNode = new Element('div', {className:'iselectstatenode'}).hide();
		this.domNode.insert(this.iselectStateNode);
		
		this.selected = false;
		this.iselected = false;
		
		this.domNode.observe('click', this._click.bind(this));	
		this.domNode.observe('mouseenter', this._mouseover.bind(this));
		this.domNode.observe('mouseleave', this._mouseout.bind(this));
	
		this.iselectStateNode.observe('click', this._toggleiSelect.bind(this));	
		this.iselectStateNode.observe('mouseover', this._iselectMouseOver.bind(this));	
		this.iselectStateNode.observe('mouseout', this._iselectMouseOut.bind(this));	
			
		// iselect from session
		if (iselect.sessionIselects[this.artworkid]) {
			
			this._setiSelectFromSession();
			
		}
	
	},

	_select: function(){
		
		if (this.selected) {
			return;
		}
		
		this.selected = true;
		
		if (this.iselected)  {
			this.iselectStateNode.setStyle({backgroundPosition:'0 -18px'});
		} else {
			this.iselectStateNode.setStyle({backgroundPosition:'0 0'});					
		}
		
		this.iselectStateNode.show();
		if (this.iselect.selected) {
			this.iselect.selected._deselect();
		}
		this.iselect.selected = this;
		
	},
	
	_deselect: function(){

		this.selected = false;
		
		if (this.iselected) {
	
			this.iselectStateNode.setStyle({backgroundPosition:'0 -35px'});
	
		} else {
		
			this.iselectStateNode.hide();				
			
		}
	
	},
	
	_setiSelectFromSession: function(){
		
		this.iselected = true;
		
		this.iselectStateNode.setStyle({backgroundPosition:'0 -35px'}).show();

	},	
	
	_toggleiSelect: function(evt){
		
		evt.stop();
		
		// iselect page? shrink node, delete & don't load in desk
		if (this.iselect.page == 'iselect') {
			
			new Ajax.Request('/' + this.contextpath + 'iselect/remove/' + this.artworkid);
			
			var self = this;
			
			// check for iSelectArtistHeader to remove
			// calc number if portfolioitems
			var numberOfItems = $('imageCol').select('div[portfoliodirectorypath="' + this.domNode.readAttribute('portfoliodirectorypath') + '"]').size();
			if (numberOfItems <= 1) {
				$('imageCol').down('a.iSelectArtistHeader[portfoliodirectorypath="' + this.domNode.readAttribute('portfoliodirectorypath') + '"]').remove();
			}
			// -- end
			
			new Effect.Shrink(this.domNode,
				{
				
					afterFinish: function(){
						self.domNode.remove();
						
						// only reset if there's a scrollbar
						// page is iselect, and user is admin: sortable support to reorder iselects.
						if ($('userrole').readAttribute('role') != 'admin') {
							var h = ComicHouse.scrollBars.get('imageCol').getScrollTop();
							ComicHouse.scrollBars.get('imageCol').reset();
							ComicHouse.scrollBars.get('imageCol').setScrollTop(h);
						}
					}
				
				}
			);
		}
		else {
			// normal operation. toggle iselect
			
			// remove help balloons
			this.iselect.getOverNodes().incl.hide();
			this.iselect.getOverNodes().excl.hide();
			
			this.iselected = (this.iselected)? false:true;
			
			if (this.iselected) {
				this.iselectStateNode.setStyle({backgroundPosition:'0 -18px'});
				var dirid = $('main').readAttribute('directoryid');
				new Ajax.Request('/' + this.contextpath + 'iselect/add/' + this.artworkid, {parameters:{directoryid:dirid}, onComplete:this._updateStatusAfterClick.bind(this)});
			} else {
				if (!this.selected) {
					this.iselectStateNode.fade({duration:.5});
				} else {
					this.iselectStateNode.setStyle({backgroundPosition:'0 0'});
				}
				new Ajax.Request('/' + this.contextpath + 'iselect/remove/' + this.artworkid, {onComplete:this._updateStatusAfterClick.bind(this)});
			}
		
		}

	},
	
	_click: function(){
		
		this._select();
		
	},
	
	_updateStatusAfterClick: function(transport){
		
		var response = transport.responseText.evalJSON();
		
		var numberOfIselectItems = (response.length == 0 || typeof response[0]!='undefined')? 0:Object.keys(response).size();
		
		if (numberOfIselectItems > 0) {
			
			ComicHouse.iselectMenu.showCheck();
			
		} else {
			
			ComicHouse.iselectMenu.hideCheck();
			
		}
		
	},
	
	_mouseover: function(){
		
		if (this.selected) {

			this.iselectStateNode.show();
			
		} else {
			
			if (this.iselected) {
				this.iselectStateNode.setStyle({backgroundPosition:'0 -52px'});
			}
			
		}
		
	},

	_mouseout: function(){
		
		if (this.selected && !this.iselected) {
			this.iselectStateNode.hide();
		}

		if (!this.selected && this.iselected) {
			this.iselectStateNode.setStyle({backgroundPosition:'0 -35px'});
		}
		
	},
	
	_iselectMouseOver: function(evt){
		
		evt.stop();
		
		var element = evt.element();
		
		if (this.selected && !this.iselected) {
			
			this.iselectStateNode.setStyle({backgroundPosition:'0 -70px'});
			
			// show includenode 'helpballoon'
			var includeNode = this.iselect.getOverNodes().incl;
			var t = element.cumulativeOffset()[1] - ComicHouse.trits.getScrollTop() - 29;
			$('imageCol').insert({after:includeNode});
			includeNode.setStyle({top:t+'px'}).show();
			
		}
		if (this.iselected) {
			
			// show excludenode 'helpballoon'
			var excludeNode = this.iselect.getOverNodes().excl;
			var t = element.cumulativeOffset()[1] - ComicHouse.trits.getScrollTop() - 29;
			$('imageCol').insert({after:excludeNode });
			excludeNode.setStyle({top:t+'px'}).show();			
			
		}

	},
	
	_iselectMouseOut: function(){
		
		// remove help balloons
		this.iselect.getOverNodes().incl.hide();
		this.iselect.getOverNodes().excl.hide();		
		
		if (this.selected && !this.iselected) {
			
			this.iselectStateNode.setStyle({backgroundPosition:'0 0px'});
					
		}		
	}
	
});


Effect.CollapseIselectMenu = Class.create(Effect.Base, {
  initialize: function(element) {
  	
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);

    var options = Object.extend({
      from: 110,
      to:   0
    }, arguments[1] || { });
    this.start(options);
  },
  setup: function(){
  	this.element.setStyle({height:'110px'});
  },
  update: function(position) {
    this.element.setStyle({height:position+'px'});
  }
});


ComicHouse.IselectMenu = Class.create (LazzoBaseClass, {
	
	_init: function(){
		
		this._observe('subtritsnavigator', this._initOnIselectLoaded.bind(this));
		
	},
	
	_initOnIselectLoaded: function() {
		
		this.CLOSED = 0; this.OPEN = 1;	this.POP = 2;

		this.menu = new Element('div', {id:'iselectmenu'});
		this.menustate = this.CLOSED;
		
		$('trits').insert(this.menu);
		this.menu.insert(new Element('div', {style:'width:1px;height:10px;'}));
		
		this.checkNode = new Element('div', {id:'iselectmenu_check'}).hide();
		this.menu.insert(this.checkNode);
		
		this._createMenuItem(ComicHouse.localizedText.iselectmenu_show, 'show');
		this._createMenuItem(ComicHouse.localizedText.iselectmenu_write, 'write');
		this._createMenuItem(ComicHouse.localizedText.iselectmenu_send, 'send');
		this._createMenuItem(ComicHouse.localizedText.iselectmenu_read, 'read');
		this._createMenuItem(ComicHouse.localizedText.iselectmenu_clear, 'clear');
		this._createMenuItem(ComicHouse.localizedText.iselectmenu_help, 'help');

		this.menu.observe('click', this._open.bind(this));
		this.menu.observe('mouseenter', this._over.bind(this));
		this.menu.observe('mouseleave', this._close.bind(this));
		
		this._checkDefaultAction();
		
		this._fireEvent('iselect-menu-loaded');
		
	},
	
	_checkDefaultAction: function() {
		
		if ($('iselectfunctions') && $('iselectfunctions').readAttribute('defaultaction').length > 0) {
			
			eval('ComicHouse.iselect_' + $('iselectfunctions').readAttribute('defaultaction') + '.show()');
			
		}
		
	},
	
	_createMenuItem: function(txt, action){
		
		var menuitem = new Element('div').update(txt);
		this.menu.insert(menuitem);

		menuitem.observe('click', this._menuItemAction.bind(this, action));

	},

	_menuItemAction: function(action, evt){

		this._close(evt);
		$$('#subtritsen_top, #subtrits_text').invoke('hide');
		
		if (!$('iselectfunctions')) {
			
			var form = new Element('form', {method:'post', action:'/' + this.contextpath + this.locale + '/iselect/show'});
			form.insert(new Element('input', {type:'hidden', name:'defaultaction', value:action}));
			document.body.insert(form);
			form.submit();
		
		} else {
		
			eval('ComicHouse.iselect_' + action + '.show()');
			
		}

	},
	
	_over: function(){
		
		this.menu.setStyle({height:'10px'});
		this.menustate = this.POP;
		
	},	
	
	_open: function(){
		
		this.menu.setStyle({height:'130px'});
		this.menustate = this.OPEN;
		
	},
	
	_close: function(evt){
		
		evt.stop();
		
		if ((this.menustate == this.CLOSED) || (this.effect && this.effect.state != 'finished')) {
				return;
			}
		
		var from = (this.menustate==this.POP)? 10:130;
		
		this.effect = new Effect.CollapseIselectMenu(this.menu, {from:from, duration:.5, afterFinish:function(){this.menustate = this.CLOSED;}.bind(this)});
		
	},
	
	showCheck: function(){
		
		this.checkNode.show();
		
	},
	
	hideCheck: function(){
		
		this.checkNode.hide();
		
	}
	
});
ComicHouse.iselectMenu = new ComicHouse.IselectMenu();

/*
 * Main iselect class to hold the current iselect session.
 * Methods:
 * - wire admin trits sort functions.
 * - 
 * - 
 */

ComicHouse.Iselect = Class.create (LazzoBaseClass, {

	_init: function() {
	
		this._observe('iselect-menu-loaded', this._initDependableLoaded.bind(this));
	
	},
	
	_initDependableLoaded: function() {
	
		// check for edit mode or non trits page -> fullstop.
		if ($('portfolio_editor') || !$('trits')) {
			return;
		}
		
		// do not use iselect on news -> full stop.
		if (this.isNews) {
			return;
		} 
		
		this.page = ($('iselecthead'))? 'iselect':'normal';
		
		this._haschanged = false;

		new Ajax.Request('/' + this.contextpath + 'iselect/get', {onComplete:this._createRows.bind(this)});
		
		// page is iselect, and user is admin: sortable support to reorder iselects.
		if (this.page == 'iselect' && $('userrole').readAttribute('role') == 'admin') {
			this._wireAdminSortFunctions();
		}
	},
	
	_writeSession: function() {
		
		this._haschanged = true;
		var newSortorder = this._getSortorder();
		
		var jsn = Object.toJSON(newSortorder);
		
		new Ajax.Request('/' + this.contextpath + 'iselect/replacesession/'+jsn);
		
	},
	
	_wireAdminSortFunctions: function() {
		
		// weird scripaculous thing
		Position.includeScrollOffsets = true;
		// custom scrollbar will interfere with drag-drop
		ComicHouse.trits.setCustomScrollBar(false);
		
		var self = this;
		
		// handles, so don's click
		$('imageCol').select('a').invoke('removeAttribute', 'href');
		
		// make sortables within every container
		$('imageCol').select('.iSelectArtistContainer').each(function(container) {
			container.identify();
			
			Sortable.create(container, {
					tag: 'DIV',
					only: 'thumbnailRow',
					constraint:'vertical',
					scroll:'imageCol',
					dropOnEmpty: true,
					onUpdate: self._writeSession.bind(self)
				}
			);

			
		});

		// make every container a sortable
		Sortable.create($('imageCol'),{
				tag: 'DIV',
				only: 'iSelectArtistContainer',
				constraint:'vertical',
				scroll:'imageCol',
				dropOnEmpty: true,
				onUpdate: self._writeSession.bind(self)
			}
		);

		
	},
	
	/*
	 * transport is the result of an ajax call and contains all session iselects in the form
	 * {artworkid1:portfolioid1,artworkidN:portfolioidN,} the order of the 'hash' is the result of the order in which the user clicked the items.
	 * this method creates an IselectRow object for each item in the trits and makes 'this' available to that object.
	 * depending the number of iselects > 0 it shows a check marker in the iselect menu. 
	 */
	_createRows: function(transport) {
		
		this.sessionIselects = transport.responseText.evalJSON();
		
		var self = this;
		
		$$('.thumbnailRow').each(function(node){
			
			new ComicHouse.IselectRow(node, self);
			
		});
		
		this._fireEvent('iselect');
		
		var numberOfIselectItems = (this.sessionIselects.length == 0 || typeof this.sessionIselects[0]!='undefined')? 0:Object.keys(this.sessionIselects).size();
		
		if (numberOfIselectItems > 0) {
		
			ComicHouse.iselectMenu.showCheck();
		
		} else {
			
			ComicHouse.iselectMenu.hideCheck();
			
		}
		
	},

	/*
	 * Return two nodes, incl and excl, as {incl:node, excl:node}.
	 */
	getOverNodes: function() {
		
		if (!this.overNodes) {
			
			var inclNode = new Element('div', {id:'iselect-include-node'});
			var exclNode = new Element('div', {id:'iselect-exclude-node'});
			
			this.overNodes = {incl:inclNode, excl:exclNode};
			
		}
		
		return this.overNodes;
		
	},
	
	/*
	 * Return if the sortorder is changed or not.
	 */
	getHasChanged: function() {
		
		return this._haschanged;
		
	},

	/*
	 * Returns the current dom sortorder as an object in the form {artworkid1:portfolioid1,artworkidN:portfolioidN}
	 */
	_getSortorder: function() {
		
		var withdirids = {};
		$$('.thumbnailRow').each(function(node) {
			var artworkid = node.readAttribute('artworkid');
			var dirid = node.previous('.iSelectArtistHeader').readAttribute('portfoliodirectoryid');
			withdirids[artworkid] = dirid;
		});
		
		return withdirids;
		
	},
	
	getSessionDirectoryIds: function(){
		
		if (!this.sessionIselects) {
			return $H();
		}
		
		var numberOfIselectItems = (this.sessionIselects.length == 0 || typeof this.sessionIselects[0]!='undefined')? 0:Object.keys(this.sessionIselects).size();
		
		if (numberOfIselectItems > 0) {
		
			var hash = $H(this.sessionIselects);
		
		} else {
			
			var hash = $H();
		}
		
		return hash.values();
	
	}
	
	

});
ComicHouse.iselect = new ComicHouse.Iselect();