/**
 * @author Vladimir Cvetic over @ ferdinand.rs
 * @version 0.20
 * @date 22.12.2008
 * @requirements Prototype >= 1.6.0.3 && Scriptaculous >= 1.8.2
 * @url http://ferdinand.rs/javascript/
**/

var ferdinand_active = false;
var PhotoTag = null;
var ferdinand_photo_url = '';

function ferdinand_toggle(){
	if (PhotoTag == null) return false;
	
	if (ferdinand_active == true){
		if (PhotoTag.square_exists=='Y') {
		//	PhotoTag.removeSquare();
		}
		ferdinand_active = false;
		$('div_ferdinand_toggle').hide();
		$('div_ferdinand_toggle_button').value = 'Pažymėk!';
		PhotoTag.tags.each(function(tag){
			try{
				tag.appear();
				tag.style.display = 'inline'; 
			}catch(err){}
		}.bind(this));
		PhotoTag.element.up().href = ferdinand_photo_url;		
	}else{
		ferdinand_active = true;
		$('div_ferdinand_toggle').appear();
		$('div_ferdinand_toggle_button').value = 'Atšaukti';
		PhotoTag.tags.each(function(tag){
			try{
				tag.hide();
			}catch(err){}
		}.bind(this));
		ferdinand_photo_url = PhotoTag.element.up().href;
		PhotoTag.element.up().href = 'javascript:';
	}
}

if (window.Ferdinand == undefined) Ferdinand = Class.create({});
Ferdinand.PhotoTag = Class.create({
	
	initialize: function(element, options){
		element = $( element );
		this.element = element;	
		
		this.tags = Array();
		this.tags_link = Array();
		
		this.options = Object.extend({
				sqsize: '150',
				sqclass: 'square-class',
				tagInputClass: 'tag-input',
				tag_square_class: 'tag_square_class',
				tag_class: 'tag_class',
				remove_link_class: 'remove_link_class',
				square_zindex: 3,
				tag_input_zindex: 4,
				tag_zindex: 2,
				lang: {
					add: 'Pridėti',
					remove: '[ X ]'
				},
				add_tag: 'p-photo_tag.html?e=add',
				get_tags: 'p-photo_tag.html?',
				remove_tag: 'p-photo_tag.html?e=remove',
				tag_ref_container: 'tag_ref_container',
				ref_ul_class: 'ref_ul_class'
			}, options || {});
		
		
		Event.observe(document.onresize ? document : window, 'resize', function(){
			//if (BrowserDetect.browser != 'Firefox')
				this.pos = $('span_imh').positionedOffset();
			//else
				//this.pos = this.element.positionedOffset();
			this.getTags();
		}.bind(this)); 

		//this.init();

		this.y_corr_tooltip = 0;
		//alert(BrowserDetect.browser);
		switch(BrowserDetect.browser){		
		case "Opera": 
			this.x_corr = 0;
			this.y_corr = -2;
			break;
		case "Explorer":
			this.x_corr = -2;
			this.y_corr = -1;
			this.y_corr_tooltip = -1;
			break;
		default:
			this.x_corr = 0;
			this.y_corr = -2;
		}

		
		
		if (this.element.complete) {
			this.init();
		} else {
			//this.element.observe('load', function(){
			//	 this.init();
			//}.bind(this));
			setTimeout('PhotoTag.init()', 1000);
		}
	},
	
	init: function (){		
		
			//if (BrowserDetect.browser != 'Firefox')
				this.pos = $('span_imh').positionedOffset();
			//else
				//this.pos = this.element.positionedOffset();			
		//alert(this.pos);
			
			this.dimensionsMode();
			if (this.mode=='%') {
				this.square_size = this.element.getWidth() * this.options.sqsize/100;
			} else {
				this.square_size = this.options.sqsize;
			}
			this.photo_id = this.element.readAttribute('photo_id');
			this.createTooltip();
			this.createTagInputBox();
			this.setEvent();
			this.getTags();	
	},	
	
	setEvent: function () {
		Event.observe(this.element, 'click', function(event){
			if (!ferdinand_active) 
				return false;
			this.setSquare(event);
		}.bind(this));
	},
	
	setSquare: function(event) {
		
		if (this.square_exists=='Y') {
			this.removeSquare();
		}
		mouseX = Event.pointerX(event);
		mouseY = Event.pointerY(event);	
		
		this.mouse = Class.create({});
		this.mouse.x = mouseX;
		this.mouse.y = mouseY;
		this.square_coord = Class.create({});

		//alert(mouseX +'-'+mouseY);
		
		this.square_coord.top = mouseY - this.square_size/2;
		this.square_coord.left = mouseX - this.square_size/2;
		
		this.square = new Element('div', {className: this.options.sqclass}).setStyle({
				position: 'absolute',
				width: this.square_size+'px',
				height: this.square_size+'px',
				top: this.square_coord.top+'px',
				left: this.square_coord.left+'px',
				zIndex: this.options.square_zindex
			});
		
		
		
		square_extra_div = new Element('div');
		this.square.appendChild(square_extra_div);
		
		//this.square.up().style.border = '1px solid red'; 
		//alert(this.square.style.top +'x'+this.square.style.left); 

		
		$('document_body').appendChild(this.square);				
		this.showTagInputBox();
		this.square_exists = 'Y';
		Event.observe(document, 'keypress', function(e){
			var code;
			if (!e) var e = window.event;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			switch (code) {
				case 27:
					this.removeSquare();
				break;
			}
		}.bind(this));
	},
	
	removeSquare: function () {
		this.square.remove();
		this.input_box.value = '';
		this.tag_input.hide();
		$(document).stopObserving('keypress');
		this.tag_input.stopObserving('keypress');
		this.square_exists = 'N';
	},
	
	createTagInputBox: function () {		
		this.tag_input = new Element('div', {className: this.options.tagInputClass}).hide();
		$('document_body').appendChild(this.tag_input);		

		html = '<input type="hidden" id="input_phototag_hidden_id"/>';
		html += '<a id="a_phototag_remove" href="javascript:" style="font-weight: normal; float: right;">[ X ]</a>';
		html += '<br/><strong>Jei norite pažymėti Motomanai.lt narį</strong><br/><small>(slapyvardis arba vardas)</small><br/>';
		html += '<input type="text" id="input_phototag_tag_member" onkeydown="return noEnters(event);" style="width: 250px"/>';
		html += '<div class="update_IE_margin"><div id="div_phototag_choices_member" class="autocomplete"></div></div>';
		html += ' <span id="span_phototag_indicator_member" style="display: none; margin-right:0px; margin-bottom:-8px"><img src="http://www.motomanai.lt/templates/tpl/images/kontentai/spinner.gif" alt="Ieškoma..." /></span>';
		html += '<br/>&nbsp;';
		html += '<br/><strong>Jei norite pažymėti motociklą</strong><br/><small>(pavadinimas ir modelis)</small><br/>';
		html += '<input type="text" id="input_phototag_tag" onkeydown="return noEnters(event);"/>';
		html += ' <div class="update_IE_margin"><div id="div_phototag_choices" class="autocomplete"></div></div>';
		html += ' <span id="span_phototag_indicator" style="display: none; margin-right:0px; margin-bottom:-8px"><img src="http://www.motomanai.lt/templates/tpl/images/kontentai/spinner.gif" alt="Ieškoma..." /></span>';
		html += ' <input type="text" id="input_phototag_tag_sub"/>';
		html += ' <input type="button" id="input_phototag_button" value="Įvesti" style="width: auto"/>';
	
		this.tag_input.innerHTML = html;
		
		this.input_box_hidden = $('input_phototag_hidden_id');
		this.tag_button_rem = $('a_phototag_remove');
		this.input_box = $('input_phototag_tag');
		this.input_box_sub = $('input_phototag_tag_sub');
		this.input_box_member = $('input_phototag_tag_member');
		this.tag_button = $('input_phototag_button');
		
		function return_get_members(elem){
			PhotoTag.input_box_hidden.value = parseInt(elem.id);
			PhotoTag.input_box_member.value = elem.title;
			PhotoTag.input_box.value = '';
			PhotoTag.input_box_sub.value = '';
			PhotoTag.submitTag();
			//$('autocomplete').clear();
		}
		function return_get_brands(elem){
			PhotoTag.input_box_hidden.value = '';
			PhotoTag.input_box_member.value = '';
			PhotoTag.input_box.value = elem.title;
			//PhotoTag.input_box_sub.value = '';			
			//$('autocomplete').clear();
		}
		new Ajax.Autocompleter("input_phototag_tag_member", "div_phototag_choices_member", 'http://www.motomanai.lt/main.php?page=photo_tag&get_members', {paramName: "search_q", minChars: 2, updateElement: return_get_members, indicator: 'span_phototag_indicator_member'});
		new Ajax.Autocompleter("input_phototag_tag", "div_phototag_choices", 'http://www.motomanai.lt/main.php?page=photo_tag&get_brands', {paramName: "search_q", minChars: 1, updateElement: return_get_brands, indicator: 'span_phototag_indicator'});

		
		this.submitEvents();
	},

	showTagInputBox: function () {
		this.tag_input.setStyle({
				position: 'relative',
				top: '-5px', //parseInt(this.square_coord.top)+parseInt(this.square_size)+'px',
				left: '8px', //parseInt(this.square_coord.left)+parseInt(this.square_size)-20+'px',
				zIndex: this.options.tag_input_zindex
		}).show();
		//this.input_box_member.focus();
		//$('input_phototag_tag_member').focus();
		Event.observe(this.tag_input, 'keypress', function(e){
			var code;
			if (!e) var e = window.event;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			switch (code) {
				case 13:
					this.submitTag();
				break;
			}
		}.bind(this));
	},
	
	submitTag: function () {
		var vars = new Hash();
		submit_x = this.mouse.x - this.pos.left;
		submit_y = this.mouse.y - this.pos.top;
		if (submit_x < this.square_size/2)
			submit_x = this.square_size/2 + 1;// + x_left;
		if (submit_y > -this.square_size/2)
			submit_y = -this.square_size/2 - 1;// + y_down;
		if (submit_x > (this.element.getWidth() - this.square_size/2))
			submit_x = this.element.getWidth() - this.square_size/2 - 3;// + x_right;
		if (submit_y < (-this.element.getHeight() + this.square_size/2))
			submit_y = -this.element.getHeight() + this.square_size/2 + 3;// + y_up;
		
		vars.set('x', submit_x);
		vars.set('y', submit_y);
		if (parseInt(this.input_box_hidden.value) > 0){
			vars.set('tag', this.input_box_member.value);
			vars.set('member_id', this.input_box_hidden.value);
		}else{
			if (this.input_box.value == ''){
				this.input_box.pulsate({duration: 0.5});
				return false;
			}
			if (this.input_box_sub.value == ''){
				this.input_box_sub.pulsate({duration: 0.5});
				return false;
			}
			vars.set('tag', this.input_box.value);
		}
		vars.set('tag_sub', this.input_box_sub.value);
		vars.set('photo_id', this.photo_id);
		
		this.input_box_hidden.value = '';
		this.input_box_member.value = '';
		this.input_box.value = '';
		this.input_box_sub.value = '';
				
		new Ajax.Request(this.options.add_tag, {
		  method: 'post',
		  parameters: vars,
		  onSuccess: function(t) {
		  	this.removeSquare();
		  	tags = t.responseText.evalJSON(true);
			this.showTags(tags);
		  }.bind(this)
		});
		
		ferdinand_toggle();
	},
	
	getTags: function() {
		var vars = new Hash();
		vars.set('photo_id', this.photo_id);
		
		new Ajax.Request(this.options.get_tags, {
		  method: 'post',
		  parameters: vars,
		  onSuccess: function(t) {
		  	tags = t.responseText.evalJSON(true);
			this.showTags(tags);
		  }.bind(this)
		});		
	},
	
	showTags: function(tags) {
		
		this.removeTags();
		
		tags.each(function(item){
			var item = item;

			leftc = parseInt(item.x)+this.pos.left-this.square_size/2 + this.x_corr;		
			topc = parseInt(item.y)+this.pos.top-this.square_size/2 + this.y_corr;

			this.tags[item.photo_tag_id] = new Element('div', {className: this.options.tag_square_class, id: 'tag-'+item.photo_tag_id});
			$('document_body').appendChild(this.tags[item.photo_tag_id]);
			
			this.tags[item.photo_tag_id].setStyle({
				position:'absolute',
				width: this.square_size+'px',
				height: this.square_size+'px',
				top: topc+'px',
				left: leftc+'px',
				zIndex: this.options.tag_zindex
			});
			
			this.tags[item.photo_tag_id].observe('mouseover', function() {
				this.showTooltip(item, true);
			}.bind(this));
			
			this.tags[item.photo_tag_id].observe('mouseout', function() {
				this.hideTooltip(item);
			}.bind(this));
			
							
		}.bind(this));
		this.showTagRefs(tags);
		
		if (ferdinand_active){
			this.tags.each(function(tag){
				tag.hide();
			}.bind(this));
		}
	},
	
	removeTags: function () {
		
		this.tags.each(function(tag){
			if (tag) {
				tag.remove();
			}
		});
		this.tags = Array();
	},
	
	showTagRefs: function (tags)
	{
		if (!$( this.options.tag_ref_container )) return false;
		
		
		$( this.options.tag_ref_container ).setStyle({width:this.element.getWidth()+'px'});
		this.refs = Array();
		this.refs_dele = Array();
		this.refli = Array();
		this.ref_ul = new Element('ul', {className: this.options.ref_ul_class});
		
		tags.each(function(item){
			var item = item;

			this.refli[item.photo_tag_id] = new Element('li');
			this.ref_ul.appendChild(this.refli[item.photo_tag_id]);
			
			if (item.member_id != null){
				this.refs[item.photo_tag_id] = new Element('a', {id: 'tagref-'+item.photo_tag_id, href: "http://www.motomanai.lt/moto-forumas/narys."+item.tag+".html"}).update(item.tag);
			}else{
				tag_ = item.tag;
				if (item.tag_sub != null)
					tag_ += ' '+item.tag_sub;
				tag_ = '<a href="http://www.youtube.com/results?search_query='+tag_+'" target="_blank" style="border: none;"><img src="http://www.youtube.com/favicon.ico" title="Ieškoti motociklo video"></a>&nbsp;' + tag_;
				this.refs[item.photo_tag_id] = new Element('span', {id: 'tagref-'+item.photo_tag_id}).update(tag_);
			}
			this.refs[item.photo_tag_id].style.fontWeight = 'bold';
			this.refs[item.photo_tag_id].style.cursor = 'pointer';
			this.refli[item.photo_tag_id].appendChild(this.refs[item.photo_tag_id]);
			
			this.refli[item.photo_tag_id].innerHTML += '&nbsp;';
			
			if (item.can_be_removed == 1){
				this.refs_dele[item.photo_tag_id] = new Element('a', {id: 'tagrefdele-'+item.photo_tag_id, href: "javascript:"}).update('<small style="font-weight:normal">(x)</small>');
				this.refs_dele[item.photo_tag_id].style.fontWeight = 'bold';
				this.refli[item.photo_tag_id].appendChild(this.refs_dele[item.photo_tag_id]);
				
				this.refs_dele[item.photo_tag_id].observe('click', function() {
					if (!confirm('Ar tikrai norite pašalinti pažymėjimą?')){
						return false;
					}
					this.hideTooltip(item);
					this.removeTag(item);
				}.bind(this));	
			}
			this.refli[item.photo_tag_id].observe('mouseover', function() {
				this.showTooltip(item, false);
			}.bind(this));
			this.refli[item.photo_tag_id].observe('mouseout', function() {
				this.hideTooltip(item);
			}.bind(this));
									
		}.bind(this));
		$( this.options.tag_ref_container ).update(this.ref_ul);
	},
	
	removeTag: function (item) {
		var vars = new Hash();
		vars.set('photo_tag_id', item.photo_tag_id);
		vars.set('photo_id', item.photo_id);
		
		new Ajax.Request(this.options.remove_tag, {
		  method: 'post',
		  parameters: vars,
		  onSuccess: function(t) {
		  	tags = t.responseText.evalJSON(true);
			this.showTags(tags);		
		  }.bind(this)
		});		
	},
	
	createTooltip: function () {
		this.tooltip = new Element('div', {className: this.options.tag_class}).hide();
		this.tooltip.setStyle({
				position:'absolute',
				zIndex: this.options.tag_zindex+1
		});
		$('document_body').appendChild(this.tooltip);
		this.tooltip.observe('mouseout', function() {
			this.hideTooltip(false);
		}.bind(this));
	},
	
	showTooltip: function (item, no_border) {
		if (no_border){
			this.tags[item.photo_tag_id].style.border = '0px';			
		}else{
			this.tags[item.photo_tag_id].style.border = '1px solid #eee';
		}
		this.tooltip.stopObserving('mouseover');
		this.tooltip.observe('mouseover', function() {
			this.showTooltip(item, false);
		}.bind(this));
		tag_ = item.tag;
		if (item.tag_sub != null)
			tag_ += ' ' + item.tag_sub;
		this.tooltip.update(tag_);
		//this.tooltip.style.top = (parseInt(item.y)+this.pos.top)+'px';
		//this.tooltip.style.left = (parseInt(item.x)+this.pos.left)+'px';		
		this.tooltip.style.top = parseInt(this.tags[item.photo_tag_id].style.top)+this.square_size/2+this.y_corr_tooltip+'px';
		this.tooltip.style.left = parseInt(this.tags[item.photo_tag_id].style.left)+this.square_size/2+'px';
		
		this.tooltip.show();
	},
	
	hideTooltip: function (item)
	{
		this.tags.each(function(tag){
			try{
				tag.style.border = '0px';
			}catch(err){}
		}.bind(this));
		this.tooltip.hide();
	},
	
	submitEvents: function () {
		this.tag_button.observe('click', function(event){
			this.submitTag();
		}.bind(this));
		this.tag_button_rem.observe('click', function(event){
			this.removeSquare();
		}.bind(this));
	},
	
	dimensionsMode: function () {
		if (this.options.sqsize.endsWith('%')) {
			this.mode = '%';
		} else {
			this.mode = 'px';
		}
		this.options.sqsize = this.options.sqsize.sub(this.mode, '', 1);
		
	}
	
});