/*
 * Author: Arnolds Verins, MRM Starsky
 * Created: 2009-05-28
 * Description: Methods for stickers
 */
var debug = true;


jQuery(document).ready(function(){
	stickerfields.init();
});

var stickerfields = new StickerFields();
function StickerFields(){
	this.opened_dropdown_sticker;
	this.animationSpeed = 550;
	
	this.init = function(){
		jQuery.estilo.tools.form.resetAllForms();
		
		// Sorry IE7 is too slow
		if(jQuery.browser.msie && jQuery.browser.version < 8){
			this.animationSpeed = 5;
		}
		try{
			var scope = this;
			// STICKERS
			var elements = jQuery('.sticker');
			for(var i=0; i < elements.length; i++){
				this.initSticker(elements[i]);
			}
			// END! STICKERS
			
			// DROPDOWNSTICKERS
			var elements = jQuery('.dropdownsticker');
			for(var i=0; i < elements.length; i++){
				var element = elements[i];
				var _select = jQuery('select', element);
				if(_select.length){
					var diff = this.initDropDown(_select);
					
					jQuery('a', element).toggle(
						function(){
							if(!jQuery(this).hasClass('disabled')){
								scope._closeAllDropDowns();
								
								var dropdownsticker = jQuery(this).closest('.dropdownsticker');
								dropdownsticker.addClass("high_z_index");
								dropdownsticker.parent().css('z-index', 5000);
								jQuery('.options', dropdownsticker).show();
								scope._updateSize(this, diff);	
								scope.opened_dropdown_sticker = dropdownsticker;
							}
						}, function(){
							var dropdownsticker = jQuery(this).closest('.dropdownsticker');
							dropdownsticker.removeClass("high_z_index");
							dropdownsticker.parent().css('z-index', 1);
							jQuery('.options', dropdownsticker).hide();
							scope._updateSize(this, diff);	
						}
					);
					jQuery('a', element)[0].onfocus = function(){ 
						this.blur();
					};
					jQuery("body").click(function(){
						scope._closeAllDropDowns();
					});
					// ---
				}
			}
			// END! DROPDOWNSTICKERS
			
			// CHECKBOXES
			jQuery('.checkbox').click(function(){
				var checkbox = jQuery('input', this)[0];
				var me = checkbox;
				var form = jQuery(this).closest('form');
				if(!form.length)
					form = document;
				
				if(!checkbox.checked){
					// Uncheck other checkboxes with the same name
					jQuery('[name=' + checkbox.name + ']').each(function(index, element){
						if(element != me){
							if(element.checked){
								jQuery(element).closest('.wrapper').removeClass("selected");
								element.checked = false;
							}
						}
					});
					
					jQuery('.wrapper', this).addClass("selected");
					checkbox.checked = true;
				}else{
					if(jQuery('[name=' + checkbox.name + ']', form).length > 1 && jQuery('[name=' + checkbox.name + ']:checked', form).length > 1){
						jQuery('.wrapper', this).removeClass("selected");
						jQuery('.wrapper input', this)[0].checked = false;
					}else{
						jQuery('.wrapper', this).removeClass("selected");
						jQuery('.wrapper input', this)[0].checked = false;
					}
				}
				jQuery(checkbox).focus();
			});
			// Init checked
			jQuery('.checkbox input:checked').each(function(index, element){
				if(element.checked){
					jQuery(element).closest('.wrapper').addClass("selected");
					element.checked = true;
				}
			});
			// END! CHECKBOXES
		}catch(ex){
			if(debug) alert(ex);	
		}
	}
	// Updates 
	this._updateSize = function(caller, diff){
		var dropdownsticker = jQuery(caller).closest('.dropdownsticker');
		// Set size
		var link_width = jQuery('a', dropdownsticker)[0].clientWidth-4;
		jQuery('.options', dropdownsticker).css("width", link_width+2 + "px");
		jQuery('.options ul', dropdownsticker).css("width", (link_width) + "px");
		jQuery('.options ul li', dropdownsticker).css("width", (link_width-20-diff) + "px");
		jQuery('.options .bottom', dropdownsticker).css("width", (link_width+2) + "px");	
	}
	this._closeAllDropDowns = function(){	
		var items = jQuery('.dropdownsticker');
		for(var i=0; i<items.length; i++){
			if(jQuery(items[i]).hasClass("high_z_index")){
				jQuery("a", items[i]).click();
			}
		}	
	}
	// -------------------------------- TYPE CHECKBOX ------------------------------------------
	this._onCheck = function(_link, _input){
		if(_input.checked || jQuery(_link).hasClass("selected")){
			jQuery(_link).removeClass("selected");
			_input.checked = false;
		}else{
			jQuery(_link).addClass("selected");
			_input.checked = true;
		}
		jQuery(_input).focus();
	}
	// -------------------------------- END! TYPE CHECKBOX -------------------------------------
	
	
	// ---------------------------------- TYPE INPUT -------------------------------------------
	this._openEdit = function(_link, input_div){
		var scope = this;
		if(!jQuery(_link).closest(".sticker").hasClass('s_disabled')){
			jQuery(input_div).parent().css('overflow', 'hidden').css('position', 'relative');
			jQuery(input_div).css("top", "-35px").css("position", "relative");
			jQuery(input_div).animate({ top:0 }, this.animationSpeed, null, function(){
				jQuery("input", input_div)[0].onblur = function(){
					scope._closeEdit(_link, input_div);
				};		
			}).show();
			jQuery("input", input_div).focus().select();
			
			jQuery(_link).css("position", "absolute").animate({
					top:35			
				},this.animationSpeed, "easeOutSine", function(){
					jQuery(this).hide();
				}
			);
		}
	}
	this._closeEdit = function(_link, input_div){
		var _input = jQuery('input', input_div)[0];
		jQuery('.label', _link).empty().append((_input.type.toLowerCase() == "password") ? '*************' : _input.value);
		
		if(jQuery.trim(_input.value) != "" && !jQuery(_link).closest(".sticker").hasClass('s_error')){
			jQuery(input_div).parent().css('overflow', 'hidden').css('position', 'relative');
			jQuery(_link).css("top", "35px").css("position", "absolute").show();
			jQuery(_link).animate({ top:0 }, this.animationSpeed, null, function(){ jQuery(this).css('position', 'relative'); }).show();
			
			jQuery(input_div).css("top", 0).css("position", "relative");
			
			jQuery(input_div).animate({
					top:-35			
				},this.animationSpeed, "easeOutSine", function(){
					jQuery(this).hide();
				}
			).show();
		}
	}
	// ---------------------------------- END! TYPE INPUT -------------------------------------------
	
	this.initDropDown = function(_select){
		try{
			var dropdownsticker = jQuery(_select).closest('.dropdownsticker');
			if(dropdownsticker.length){
				// Add DIV based dropdownlist
				var html = '<div class="options"><ul>' + jQuery(_select).html() + '</ul><div class="bottom"><div class="corner"></div></div></div>';
				html = html.replace(/<option.*?>/gi, '<li>').replace(/<\/option>/gi, '</li>');
				jQuery('.options', dropdownsticker).remove();
				jQuery(dropdownsticker).append(html);
				var link_width = jQuery('a', dropdownsticker)[0].clientWidth-4;
				
				jQuery('.options', dropdownsticker).show();
				var diff = (jQuery('.options ul', dropdownsticker)[0].clientHeight > 100) ? 15 : 0;
				jQuery('.options', dropdownsticker).hide();
				if(diff) jQuery('ul', dropdownsticker).addClass("dropdownsticker_max_height");
				// ---
				// Set selected value
				jQuery('a .label', dropdownsticker).empty().append(jQuery(jQuery('option:selected:first', dropdownsticker)).text());	
				// ---
					
				// Click event for options in DIV-based dropdown
				jQuery('.options li', dropdownsticker).click(function(){
					var dropdownsticker = jQuery(this).closest('.dropdownsticker');
					var selectedIndex = jQuery("li", this.parentNode).index(this);
					var _select = jQuery('select', dropdownsticker)[0];
					if(selectedIndex >= 0)
						_select.selectedIndex = selectedIndex;
					jQuery('a .label', dropdownsticker).empty().append(jQuery(this).text());	
					jQuery('a', dropdownsticker).click();	
					
					jQuery(_select).focus();
				});
				// Hover effects
				jQuery('.options li', dropdownsticker).hover(
					function(){
						jQuery(this).addClass("hover");					
					}, function(){
						jQuery(this).removeClass("hover");									
					}
				);
				return diff;
			}
		}catch(ex){
			if(debug) alert("Error in initDropDown: " + ex);
		}
	}
	this.reInitDropDown = function(dropdownsticker) {
		// Click event for options in DIV-based dropdown
		try {
			var _select = jQuery("select", dropdownsticker)[0];
			jQuery('.options li', dropdownsticker).click(function(){
				var dropdownsticker = jQuery(this).closest('.dropdownsticker');
				var selectedIndex = jQuery("li", this.parentNode).index(this);
				var _select = jQuery('select', dropdownsticker)[0];
				if(selectedIndex >= 0)
					_select.selectedIndex = selectedIndex;
				jQuery('a .label', dropdownsticker).empty().append(jQuery(this).text());	
				jQuery('a', dropdownsticker).click();	
				alert("hej");
				jQuery(_select).focus();
			});
			// Hover effects
			jQuery('.options li', dropdownsticker).hover(
				function(){
					jQuery(this).addClass("hover");					
				}, function(){
					jQuery(this).removeClass("hover");									
				}
			);		
		} catch (ex) {
			if (debug) 
				alert("Error in reInitDropDown: " + ex);
		}
	}
	this.initSticker = function(sticker_div){
		var scope = this;
		var element = jQuery(sticker_div)[0];
		var _input = jQuery('input', element);
		var _link = jQuery('a', element)[0];
		if(_input.length){
			_input = _input[0];
			_link.parent = element;
			_link.type = _input.type;
					
			switch(_input.type.toLowerCase()){
				case 'password':
					if(_input.value)
						jQuery('.label', sticker_div).empty().append((_input.type.toLowerCase() == "password") ? '*************' : _input.value);
				case 'text':
					// Set input value
					_input.value = jQuery.trim(jQuery('a .label', element)[0].innerHTML.replace(/&nbsp;/i, ''));
					_input.value = unescape(escape(_input.value).replace(/%A0/i, '')); // Safari
					
					_input.parent = element;
					if(jQuery.trim(_input.value).length == 0) {
						jQuery(_link).hide();
						jQuery(".input", element).show();
						if (!jQuery(_link).hasClass("always_editable")) {
							_input.onblur = function(){
								scope._closeEdit(jQuery('a', this.parent)[0], jQuery('.input', this.parent)[0]);								
							};
						}
					}
					_link.onclick = function(){
						scope._openEdit(this, jQuery('.input', this.parent));								
					};
					_link.onfocus = function(){ this.blur(); };
					jQuery(_input).keyup(function(event){
						// ENTER
						if (event.keyCode == 13) {
							this.blur();
						}
						// ESC	
						else if(event.keyCode == 27){}
					}); 
					break;
				case 'radio':
				case 'checkbox':
					if(jQuery(element).hasClass('editable')){
						_link.input = _input;
						_link.onfocus = function(){ this.blur(); };
						if (jQuery(element).hasClass('radio')) {
							_link.onclick = function() {
								jQuery(element).closest('.wrapper').find('.radio').each(function(i) {
									var lnk = jQuery(this).find("a");
									if (this == sticker_div) {
										lnk.addClass("selected");
										jQuery('input', this).focus();
									} else {
										lnk.removeClass("selected");
										lnk.blur();
									}
								});	
								return false;								
							};
						} else {
							_link.onclick = function() {
								scope._onCheck(this, this.input);
								return false;
							}
						}
						if(_input.checked) 
							jQuery(_link).addClass("selected");
					}else{
						jQuery(_link).css('cursor', 'default');
						_link.onclick = function(){							
							this.blur();
							return false;	
						}
					}
					break;
			}
		}
	}
	
	this.setStickerWidth = function(sticker_div){
		jQuery('.stickers').css('width', '600px');
		setTimeout(function(){		
			var link_width = jQuery('a', sticker_div).width();
			if(link_width > 0){
				link_width += 10;
				jQuery(sticker_div).css('width', link_width + 'px');	
			}
		}, 1550);
	}
}