/**
* Teeko Framework Javascript GetElementClasses class
*
* @copyright (C) 2009 Webisti Oy. All rights reserved
* @version 1.0
* @author Eemeli Söderholm <eemeli.s@webisti.fi>
*/


STARTED_TO_EDIT_PAGE = false;
MARKED_ELEMENT_HIDDEN = false;

LAST_ELEMENT_CLICKED = false;

var global_marked_element = false;
var global_resize_handler = true;
/*
$.fn.loadTemplate = function(container)
{
	Request($(this).attr('template'),{'dest':container, 'method':'get'});
};
*/
$.fn.anim = function(options, speed)
{
	el = $(this);
	
	if(options == 'ORIGINAL')
	{
		var parms = eval('(' + el.attr('orig_pos') + ')');
		el.animate(parms, speed);
	}
	else
	{
		if(!el.attr('orig_pos')) el.attr('orig_pos', "{width:'"+el.css('width')+"',height:'"+el.css('height')+"',left:'"+el.css('left')+"',top:'"+el.css('top')+"'}");
	
		el.animate(options, speed);
	}
};

jQuery.fn.position = function()
{
	var pos = {};
	
	if($(this).parent().hasClass('element_wrapper'))
	{
		pos.left = parseInt($(this).parent().css('left'));
		pos.top = parseInt($(this).parent().css('top'));
	}
	else
	{
		pos.left = parseInt($(this).css('left'));
		pos.top = parseInt($(this).css('top'));
	}	
	
	return pos;
}

jQuery.fn.changeImage = function(dest)
{
	var img = new Image();

	$(dest).parent().append('<div class="image_loader" style="display:none;top:0px;left:0px;width:100%;height:100%;position:absolute;background: url(images/37-1.gif) no-repeat center center;opacity:0.5" />').find('.image_loader').fadeIn();

	$(img).load(function()
	{ 
		$(dest).attr('src',this.src).show();

		$(dest).parent().find('.image_loader').remove();
		
	})
	.error(function()
	{
	})
	.attr('src', $(this).attr('src_on'));	
}

jQuery.fn.doAnim = function(sFrame, eFrame, speed)
{ 
	var el = $(this);

	if(el.attr('backgroundInt')) clearInterval(el.attr('backgroundInt'));

	if(isNaN(parseInt(el.attr('backgroundStep')))) el.attr('backgroundStep', 0);

	var steps = Math.abs(sFrame - eFrame);
	var stepHeight = el.css('height');
	
	animBackground = function (el, sFrame, eFrame, steps){
		if(sFrame > eFrame){ if(parseInt($(el).attr('backgroundStep')) > 0) $(el).attr('backgroundStep',parseInt($(el).attr('backgroundStep'))-1);}else $(el).attr('backgroundStep',parseInt($(el).attr('backgroundStep'))+1);

		$(el).css('backgroundPosition','0px -'+(parseInt(stepHeight) * $(el).attr('backgroundStep'))+'px');
		if ($(el).attr('backgroundStep') > steps || $(el).attr('backgroundStep') <= 0) clearInterval($(el).attr('backgroundInt'));
	}

	el.attr('backgroundInt', setInterval("animBackground('#"+el.attr('id')+"',"+sFrame+","+eFrame+","+steps+")", speed));
}
	
jQuery.fn.element = function() 
{
	// Tähän tulee functio jota kutsutaan tyyliin $(this).realElement();
	//ja se palauttaa sen resizable elementin oikean elementin eli sen mitä ollaan oikeasti muuttelemassa
	// Tässä pitää ottaa huomioon että imagessa taas otetaan css tiedot wrappi elementistä koska
	// kuva on laitettu 100% width ja height niin se ei hyödytä mut muut taas toimii.. tähän vois tehä
	// switch casen millä katotaan erikseen erilailla kaikki eri elementti tyylit!

	// Element wrapper is same thing that .resizable element so
	var element_wrapper = ($("#"+$(this).attr('id')+".element_wrapper:first").attr('id'));	
	var resizable_element = $("#"+element_wrapper+" > .resizable:first");
	
	return resizable_element;
	
	/*
	$('#'+this.attr('id')+" *").each(function()
	{
//		if($(this).attr('class') == 'resizable')
//		{
			ids += $(this).attr('id')+" - "+$(this).attr('class')+ "\n";	
//		}
	});*/
	//return $(this);
}

jQuery.fn.wrapper = function() 
{
	var element_wrapper = ($("#"+$(this).attr('id')+".element_wrapper:first"));
//	var element_wrapper = $(this).find(".element_wrapper:first");
	
	return element_wrapper;
//	var resizable_element = $("#"+element_wrapper+" > .resizable:first").attr('id');
	
	/*
	$('#'+this.attr('id')+" *").each(function()
	{
//		if($(this).attr('class') == 'resizable')
//		{
			ids += $(this).attr('id')+" - "+$(this).attr('class')+ "\n";	
//		}
	});*/
	//return $(this);
}

jQuery.fn.screenshot = function(append_element) 
{
/*
	$(append_element).append("<div id='screenshot' style='overflow:auto;z-index:9999;background-color:white;position:absolute;left:50px;top:50px;width:400px;height:500px'></div>");

	//$("#main_container").clone().appendTo('#screenshot');
		
	$("#main_container .resizable").each(function()
	{	
		$(this).clone().attr('id',$(this).attr('id')+"_screenshot").appendTo('#screenshot');
//		$(this).attr('id',$(this).attr('id')+'_screenshot');

		$('#'+$(this).attr('id')+'_screenshot').css('width','10px');
		$('#'+$(this).attr('id')+'_screenshot').css('height','10px');
		$('#'+$(this).attr('id')+'_screenshot').css('font-size','2px');		
//		$(this).clone().attr('id', $(this).attr('id')+'_screenshot').appendTo("#screenshot");
		/*
		$(this).find(':child.resizable').each(function()
		{	
		$('#'+$(this).attr('id')+'_screenshot').css('width','50px');
		$('#'+$(this).attr('id')+'_screenshot').css('font-size','2px');		
		});
		*/		
//		$('#'+$(this).attr('id')+'_screenshot').css('width','20px');
		
//	});

//	Request('function/XML/GetScreenshot',"{'async':'false', 'append':'true', 'dest':'screenshot', 'method':'get'}","{'file':'sites/torsti/action/app/main/show.xml'}");
}

jQuery.fn.overlay = function() 
{
	var element_overlay = $(this).find(".element_overlay:last");
	
	return element_overlay;
//	var resizable_element = $("#"+element_wrapper+" > .resizable:first").attr('id');
	
	/*
	$('#'+this.attr('id')+" *").each(function()
	{
//		if($(this).attr('class') == 'resizable')
//		{
			ids += $(this).attr('id')+" - "+$(this).attr('class')+ "\n";	
//		}
	});*/
	//return $(this);
}

ElementSendToServer = function( mElements )
{
	Request('function/session/SetElement', "{'method':'get'}", {'elements':mElements} );
}

ElementModify = function( mElements )
{
	if(typeof mElements === 'object')
	{
		var all_elements = {};
		var element_css = {};
		var element_attribute = {};

		$.each(mElements,function(i,item) 
		{
			var element_id = i;
			var element_parent_id = $("#"+element_id).parent().parent().attr('id');
			var element_tagname = $("#"+element_id).attr('tagName');

			if(item.css !== undefined)
			{
				$.each(item.css,function(i,item) 
				{
					if(item == true && $("#"+element_id).css(i) != null)
					{
						// All css modifys (width, top, left etc..)
						if(i=='left' || i=='top' || i=='margin-left') 
							element_css[i] = $("#"+element_id).parent().css(i);
						else
							element_css[i] = $("#"+element_id).css(i);
					}
				});
			}
			
			if(item.attribute !== undefined)
			{
				$.each(item.attribute,function(i,item) 
				{
					if(item == true && $("#"+element_id).attr(i) != null)
					{
						// All attribute modifys (attr() function, src, value etc..)
						element_attribute[i] = $("#"+element_id).attr(i);
					}
				});
			}

			// Collect all information and return whole json array
			if($("#"+element_id).attr('type') == 'text') 
			{
				element_attribute.value = $("#"+element_id).html();
				element_tagname = 'text';
			}
			
			all_elements[element_id] = {}
			all_elements[element_id].type = element_tagname;
			all_elements[element_id].parent = element_parent_id;	
			all_elements[element_id].css = element_css;
			all_elements[element_id].attribute = element_attribute;
		});
		
		return all_elements;
	}

	return false;
}

var saved_event;

jQuery.fn.stopDrag = function(options) 
{
/*
	var this_height = parseInt($(this).css('height').replace('px','')) + parseInt($(this).css('top').replace('px',''));

	if(this_height > parseInt($(this).parent().css('height').replace('px','')) && $(this).parent().css('overflow') == 'hidden')
	{
		$(this).parent().css('height',this_height+"px");
	}
*/
	var el = $(this).element();

	var modified_elements = {};
	modified_elements[el.attr('id')] = {'css':{'font-size':true, 'color':true, 'font-family':true, 'background-image':true, 'background-color':true, 'background-repeat':true, 'margin-left':true, 'position':true, 'top':true, 'left':true, 'width':true, 'height':true}, 'attribute':{'src':true, 'value':true}};
	
	var all_elements = ElementModify( modified_elements );
	
	ElementSendToServer( all_elements );
	//$("#"+element_id).bind('click', saved_event['click']);
//		alert(saved_event['click'][86]);

//	alert(saved_event['click'][86]);
//	$("#"+element_id).bind(saved_event['click'][86]);
//	$.event.add(this, 'click', saved_event['click'][86], saved_event['click'][86].data);
/*
	for (var handler in saved_event['click'])
		$.event.add(this, 'click', saved_event['click'][handler], saved_event['click'][handler].data);
*/
}

jQuery.fn.startDrag = function(options) 
{
					
/*
	saved_event = $.data(this[0], 'events');

	$("#"+element_id).unbind('click');

	
	for (var handler in saved_event['click'][86])
		alert(handler);*/
//		$.event.add(this, 'click', saved_event['click'][handler], saved_event['click'][handler].data);

	/*
	for (var type in saved_event['click'])
	{
		alert(type);
	}
	*/
//	alert(saved_event['click']);
}
/*
jQuery.fn.ReloadImage = function(parms, resize, PRELOADER_TIMEOUT)
{
	if(typeof(PRELOADER_TIMEOUT) == 'undefined') PRELOADER_TIMEOUT = 1000; 

	if(this.attr('tagName') == 'IMG') 
	{
		var el = $(this);

		var src = el.attr('src_old');
		if(!src) 
		{
			src = el.attr('src');
			el.attr('src_old', src);
		}

		var img = new Image();

		if(typeof parms === 'string') parms = eval('(' + parms + ')');

		parms = JSON.stringify(parms);

		if(typeof parms === 'undefined')
		{
			return false;
		}

		args_str = "args=" + encodeURIComponent($.base64.encode(parms));
		
		$(img).attr('preloader', setTimeout(function() 
		{
			el.parent().append('<div class="image_loader" style="display:none;top:0px;left:0px;width:100%;height:100%;position:absolute;background: url(images/imageloader.gif) no-repeat center center;background-color:#000;opacity:0.5" />').find('.image_loader').fadeIn();
		}, PRELOADER_TIMEOUT));
		
		$(img).load(function()
		{ 
			// DEBUG: Hidastaako tää vai ottaako cachesta suoraan kun $(img) sisältäis jo ladatun kuvan
			// niin kun täähän lataa sen uudestaan? mutta lataako vai saako se suoraan sen
			// annettua? tietysti tässä tulee turhaan 2 http pyyntöä tietystikin ?!?
			// ei viittis removaa eka tota aikasempaa ja sitten insertoida uutta vaan miten ton img sais suoraan tolle el:elementille
			
			el.attr('src',this.src);
						
			clearTimeout($(this).attr('preloader'));
			$(this).removeAttr('preloader');
			
			el.parent().find('.image_loader').remove();
			
			if(resize === true)
			{
			  // calculate original width and height 
	//		  	var oh = parseInt(el.css('height'));
	//		  	var ow = parseInt(el.css('width'));
				
				// KAIKILLA elementeillä pitäis pitää kokoajan attributeissa alkuperästä kokoa
				// eli myös kuvakoko jolla voidaan sitten laskea ero alkuperäsen ja sivulla olevan
				// niin voidaan tässä resizaa suhteessa siihen kokoon mikä on sivulla kun jos asiakas
				// on resizannu kuvaa 50% pienemmäks niin kun laittaa esim. reflectionin ni se 
				// suurentaa sen alkuperäseen + reflectionin koko. tietysti sen vois myös kattoo 
				// alkuperäsestä kuvafileestä sen koon?!?!?!
			  //	el.animate({height:this.height, width:this.width}, 100).parent().animate({height:this.height, width:this.width}, 100);
			  	
//				el.parent().css({height:this.height, width:this.width});
				el.css({height:this.height, width:this.width});
				el.animate({height:this.height, width:this.width}, 100);
			}
			
		})
		.error(function()
		{
			alert('Virhe ladatessa kuvaa')
		})
		.attr('src', src + "?"+args_str);		
	}
}*/

jQuery.fn.stopResize = function(options) 
{
	var el = $(this).element();

	var modified_elements = {};
	modified_elements[el.attr('id')] = {'css':{'font-size':true, 'color':true, 'font-family':true, 'background-image':true, 'background-color':true, 'background-repeat':true, 'margin-left':true, 'position':true, 'top':true, 'left':true, 'width':true, 'height':true}, 'attribute':{'src':true, 'value':true}};
	
	var all_elements = ElementModify( modified_elements );
	
	ElementSendToServer( all_elements );

	el.addEffect({method:"resize",width:parseInt(el.css('width')),height:parseInt(el.css('height'))});

	$(".editor-selected").teeko('element','reload', options);	
	//el.ReloadImage( $(".teeko-selected").attr('effects') );
}

function GetElementAttributes(element_id)
{
	return {left:$(element_id).css('left').replace('px',''), top:$(element_id).css('top').replace('px',''),
			width:$(element_id).css('width').replace('px',''),height:$(element_id).css('height').replace('px',''),
			opacity:$(element_id).element().css('opacity'), zindex:$(element_id).css('zIndex')}
}

jQuery.fn.drag = function(options) 
{
	json_attr = GetElementAttributes("#"+$(this).wrapper().attr('id'));	
	UpdateControlPanel(json_attr);
}


jQuery.fn.resize = function(options) 
{
	json_attr = GetElementAttributes("#"+$(this).wrapper().attr('id'));	
	UpdateControlPanel(json_attr);	
}

jQuery.fn.startResize = function(options) 
{
	var rOptions = {};
	var minWidth = 0, minHeight = 0;
	var element = $(this);

	$(this).find(".element_wrapper").each(function()
	{
		var width = $(this).css('width');
		var height = $(this).css('height');
		var left = $(this).css('left');
		var right = $(this).css('right');
		var top = $(this).css('top');
						
		if(height.charAt(height.length-1) == '%')
		{
			height = $("#"+element_id).css('height') / height.replace('%','');
		}
						
		if(width.charAt(width.length-1) == '%')
		{
			width = $("#"+element_id).css('width') / width.replace('%','');
		}
						
		if(left.charAt(left.length-1) == '%')
		{
			left = $("#"+element_id).css('left') / left.replace('%','');
		}

		if(top.charAt(top.length-1) == '%')
		{
			top = $("#"+element_id).css('top') / top.replace('%','');							
		}
						
		top = parseInt(top);
		left = parseInt(left);
		right = parseInt(right);
		width = parseInt(width);
		height = parseInt(height);

/*
						if(isFinite(right) == true) 
						{
							left = right;
						}
*/						
		if((width + left) > minWidth)
		{
			minWidth = width + left;
		}

		if((height + top) > minHeight)
		{						
			minHeight = height + top;
		}
						
		if(isFinite(minWidth) == true) 
		{							
			rOptions.minWidth = minWidth;
		}
						
		if(isFinite(minHeight) == true) 
		{						
			rOptions.minHeight = minHeight;
		}

	});
	if(minHeight == 0) minHeight = 10;
	if(minWidth == 0) minWidth = 10;
					
	$(element).resizable('option', 'minHeight', minHeight);
	$(element).resizable('option', 'minWidth', minWidth);					
}



jQuery.fn.tresizable = function(options) 
{
	
	$("#main_container").disableSelection();
	
	$(this).each(function()
	{
		if($(this).length > 0 && $(this).attr('id') && $(this).attr('resizable') !== 'true')
		{			
			var jOptions = {};

			var rOptions = {};
		
			// Create wrapper div only if element is not already div (ex. img)
			var element_id = $(this).attr('id');
			var original_element_id = $(this).attr('id');

			$(this).attr('resizable', true);
			
//			if($(this).attr('tagName') !== 'DIV')
//			{   
				var parent_index = $(this).parent().css('zIndex');
				if(parent_index == 'auto')
				{
					$(this).parent().css('zIndex',1);
					parent_index = 1;
				}
				
				var wrapper_element = $(this).attr('id')+"_wrap";
				
				$(this).wrap("<div class='element_wrapper' id='"+wrapper_element+"'></div>");				
				
				if($(this).css('overflow') =='auto')
				{
//					$("#"+wrapper_element).css('width', parseInt($(this).css('width'))+30+'px' );
				}
				else
				{
				}

					$("#"+wrapper_element).css('width', $(this).css('width') );

				$("#"+wrapper_element).css('height', $(this).css('height') );
				$("#"+wrapper_element).css('position', $(this).css('position') );							
				$("#"+wrapper_element).css('left', $(this).css('left') );
				$("#"+wrapper_element).css('right', $(this).css('right') );
				$("#"+wrapper_element).css('top', $(this).css('top') );
				$("#"+wrapper_element).css('marginLeft', $(this).css('marginLeft') );
				$("#"+wrapper_element).css('marginTop', $(this).css('marginTop') );
				$("#"+wrapper_element).css('bottom', $(this).css('bottom') );
				$("#"+wrapper_element).css('pointer', 'move' );
//				$("#"+wrapper_element).css('overflow', $(this).css('overflow') );
//				$("#"+wrapper_element).css('overflow','hidden' );

//				$("#"+wrapper_element).css('zIndex', $(this).css('zIndex'));
				$("#"+wrapper_element).css('zIndex', parent_index + 1);

				if($(this).hasClass('editable'))
					$("#"+wrapper_element).append("<div id='"+$(this).attr('id')+"_overlay' class='element_overlay' style='z-index:9999;opacity:0.2;background-color:black;cursor:move;position:absolute;left:0px;top:0px;width:100%;height:100%;'/>");
					
//				$(this).copyEventsTo("#"+wrapper_element);

				$("#"+wrapper_element).prepend('<div style="z-index:1000;background:url(images/resize_line.png);width:100%;height:3px;position:absolute;left:0px;top:-10px;" class="ui-resizable-handle ui-resizable-nline"></div>');
				$("#"+wrapper_element).prepend('<div style="z-index:1000;background:url(images/resize_line.png);width:100%;height:3px;position:absolute;left:0px;bottom:-10px;" class="ui-resizable-handle ui-resizable-sline"></div>');
				
				$("#"+wrapper_element).prepend('<div style="z-index:1000;background:url(images/resize_line.png);height:100%;width:3px;position:absolute;right:-10px;top:0px" class="ui-resizable-handle ui-resizable-eline"></div>');
				$("#"+wrapper_element).prepend('<div style="z-index:1000;background:url(images/resize_line.png);height:100%;width:3px;position:absolute;left:-10px;top:0px;" class="ui-resizable-handle ui-resizable-wline"></div>');

				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-n"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');
				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-s"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');
				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-sw"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');
				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-se"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');
				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-nw"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');
				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-ne"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');
				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-w"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');
				$("#"+wrapper_element).prepend('<div style="-moz-user-select: none;" unselectable="on" class="ui-resizable-handle ui-resizable-e"><img class="ui-resizable-box ui-resizable-handle" src="images/resize_box.png"/></div>');

				$(this).css( {'overflow':$(this).css('overflow'),'z-index':$(this).css('zIndex'),top:'0px',left:'0px',right:'','position':'static','marginLeft':'0px','marginTop':'0px' } );

				element_id = wrapper_element;

	  			rOptions.alsoResize = '#'+$(this).attr('id');
				
		//	}
		//	else
		//	{
//				$("#"+element_id).css('overflow', 'hidden');
			//	$("#"+element_id).attr('class', $("#"+element_id).attr('class') + ' element_wrapper');

			//	$("#"+element_id).prepend("<img id='"+$(this).attr('id')+"_overlay' style='opacity:0;display:none;position:absolute;width:100%;height:100%;' src='images/blue_rec.png'/>");
			//	$("#"+element_id).css('overflow', 'scroll' );
		//	}
			
			jOptions.grid = [10, 10];
//  			jOptions.distance = 40;

      		$("#"+element_id).append('<img id="'+element_id+'_pulse" style="left:50%;top:50%;margin-left:-20px;margin-top:-25px;position:absolute;width:10px;height:10px;display:none;" src="images/pulse2.png">');
/*
		   	$("#"+element_id).hover( function () 
		   	{
				if($(this).attr('dragging') == 'false')
				{
	       			$("#"+$(this).attr('id')+"_overlay").show().animate({opacity:"0.2"},200);
	       		}
      		}, function () 
      		{
         		if($(this).attr('tagName') == 'DIV')
		 		{
           			$("#"+$(this).attr('id')+"_overlay").animate({opacity:"0"},200).hide();
         		}
      		});
  */    		
			if($("#"+element_id).parent() && options.parent_drag == true)
			{
//				jOptions.containment = 'parent';
//				rOptions.containment = 'parent';
			}
			
//			jOptions.autoHide = true;
			jOptions.zIndex = 999;
			jOptions.opacity = 0.5;
			
			jOptions.stop = function() { $(this).stopDrag(); };
			jOptions.start = function() { $(this).startDrag(); };
			jOptions.drag = function() { $(this).drag(); };
			
//			rOptions.handles = "sw,nw,w,n,ne,e,se,s";
			rOptions.handles = {e:'.ui-resizable-e .ui-resizable-box',w:'.ui-resizable-w .ui-resizable-box',n:'.ui-resizable-n .ui-resizable-box',s:'.ui-resizable-s .ui-resizable-box',se:'.ui-resizable-se .ui-resizable-box',sw:'.ui-resizable-sw .ui-resizable-box',ne:'.ui-resizable-ne .ui-resizable-box',nw:'.ui-resizable-nw .ui-resizable-box'};
//			rOptions.ghost = true;
//			rOptions.animate = true;
			rOptions.opacity = 0.5;
			rOptions.stop = function() { $(this).stopResize(); };
			rOptions.start = function() { $(this).startResize(); };
			rOptions.resize = function() { $(this).resize(); };

			$("#"+element_id).dblclick( function(e) 
			{
				if($(this).element().hasClass('editable'))
				{
					if($('#'+element_id+'_iframe_dest').length == 0)
					{
						$(this).wrapper().append('<div id="'+element_id+'_iframe_dest" style="width:100px;height:10px;position:absolute;top:-40px;left:0px;display:none"><input id="'+element_id+'_iframe_dest_input"></input></div>');
						$('#'+element_id+'_iframe_dest').keyup(function(e) 
						{
							if(e.keyCode == 13) 
							{
								var value = $('#'+element_id+'_iframe_dest_input').val();
								
								$("#"+element_id).element().attr('src','http://'+value);
							}
						});		
					}
					$("#"+element_id+"_iframe_dest").show('slide',200);
					$(this).overlay().hide();				
				}
				
				switch($(this).element().attr('type'))
				{
					case 'text':
						$(this).element().hide();
						$(this).element().addClass("editable");					
						var htmli = $(this).element().html();

//						$(this).wrapper().append('<textarea id="'+$(this).element().attr('id')+'_edit" style="border:0px;background:transparent;position:absolute;top:0px;left:0px;width:100%;height:100%;overflow:hidden;font-family:'+$(this).element().css('fontFamily')+';font-size:'+( $(this).element().css('fontSize').replace('px','') - 0.6) +'px;color:'+$(this).element().css('color')+'">'+htmli+'</textarea>');
						$(this).wrapper().append('<iframe id="'+$(this).element().attr('id')+'_edit" style="border:0px;background:transparent;position:absolute;top:0px;left:0px;width:100%;height:100%;overflow:hidden;font-family:'+$(this).element().css('fontFamily')+';font-size:'+( $(this).element().css('fontSize').replace('px','') - 0.6) +'px;color:'+$(this).element().css('color')+'"></iframe>');

						$("#"+$(this).element().attr('id')+'_edit').get(0).contentWindow.document.designMode = "on"
						$("#"+$(this).element().attr('id')+'_edit').contents().find("body").html(htmli);
												
						$("#"+$(this).element().attr('id')+'_edit').html(htmli).select();
						//$("#"+$(this).element().attr('id')+'_edit').execCommand('bold');
						break;
				}
/*				$("#lower_toolbar_titlebar").click();
				$("#lower_toolbar_button_font").click();
				$("#editor_office2003").attr('value','BLAABLAABLAA');
				// stopPropagation pitää käyttää sentakii et kaikki ko. elementin alla olevat elementit liipasee
				// myös click:in ja tää keskeyttää täksi ajaksi kaikki eventit jolloin ei niin tapahdu*/
				e.stopPropagation();
			});
			
			$("#"+element_id).click( function(e) 
			{
				if($(LAST_ELEMENT_CLICKED).element().hasClass('editable') && $(LAST_ELEMENT_CLICKED).wrapper().attr('id') !== $(this).wrapper().attr('id'))
				{
					$("#"+$(LAST_ELEMENT_CLICKED).attr('id')+"_iframe_dest").hide('slide',200);
					$(LAST_ELEMENT_CLICKED).overlay().show();
					
					switch($(LAST_ELEMENT_CLICKED).element().attr('type'))
					{
						case 'text':
							$(LAST_ELEMENT_CLICKED).element().html( $('#'+$(LAST_ELEMENT_CLICKED).element().attr('id')+'_edit').contents().find("body").html() );

							$('#'+$(LAST_ELEMENT_CLICKED).element().attr('id')+'_edit').remove();
							
							$(LAST_ELEMENT_CLICKED).element().show().removeClass('editable');
							break;
					}
					
				}

				$(LAST_ELEMENT_CLICKED).element().removeClass('teeko-selected');
				
				LAST_ELEMENT_CLICKED = $(this);

				
		  		$("#main_container").find(".ui-resizable-eline, .ui-resizable-wline, .ui-resizable-nline, .ui-resizable-sline, .ui-resizable-e, .ui-resizable-w, .ui-resizable-n, .ui-resizable-nw, .ui-resizable-ne, .ui-resizable-sw, .ui-resizable-se, .ui-resizable-s").css("display","none");
			
				if(!$(this).hasClass('ui-draggable'))
				{
					$(this).draggable(jOptions).resizable(rOptions);
				}
				
		  		$(this).wrapper().find(".ui-resizable-eline:first, .ui-resizable-wline:first, .ui-resizable-nline:first, .ui-resizable-sline:first, .ui-resizable-e:first, .ui-resizable-w:first, .ui-resizable-nw:first, .ui-resizable-ne:first, .ui-resizable-n:first, .ui-resizable-sw:first, .ui-resizable-se:first, .ui-resizable-s:first").css("display","block");
		  		
				json_attr = GetElementAttributes("#"+$(this).wrapper().attr('id'));	
				UpdateControlPanel(json_attr);

				global_marked_element = '#'+$(this).attr('id');
				$(this).element().addClass('teeko-selected');
				
				if(MARKED_ELEMENT_HIDDEN === false && e.altKey === true)
				{
					MARKED_ELEMENT_HIDDEN = true;
					$(this).teeko_effects_show('background');
					$("#element_hider").click( function(e) {MARKED_ELEMENT_HIDDEN = false;});
					e.stopPropagation();
				}	

					rOptions.maxHeight = $(this).wrapper().parent().parent().css('height');
					rOptions.maxWidth = $(this).wrapper().parent().parent().css('width');

				if(e.shiftKey === true)
				{				
//					rOptions.aspectRatio = true;
				}
				else
				{
					// DEBUG: Tää vois olla pelkkä .resizable mutta jostain syystä se ei toimi kunnolla 
					// ainakaan siinä tapauksessa kun laitetaan uus elementti ruudulle niin sen resizable
					// ei poistu kun painaa jotain muuta elementtiä mutta #main_container * se poistaa sen :)
					
//		   			$("#main_container *").not(this).draggable('destroy');
		   			//$(this).find(".ui-resizable-handle").css("display","none !important");
//		   			$(this).find(".ui-resizable-handle").css("display","none !important");
		   			
		   			$("#main_container *").not(this).attr('dragging', false);

					rOptions.aspectRatio = false;
					var minWidth = 0;
					var minHeight = 0;
					
					rOptions.maxHeight = $("#"+$(this).attr('id')).css('height');
					rOptions.maxWidth = $("#"+$(this).attr('id')).css('width');

//					$("#"+$(this).wrapper().attr('id')+" * .element_wrapper").each(function()

				}

				if($(this).attr('dragging') == 'false' || $(this).attr('dragging') == undefined)
				{
					$("#"+$(this).attr('id')+'_pulse').css({opacity:"1", width:"10px", height:"10px", 'marginLeft':'-10px','marginTop':'-5px'});
           			$("#"+$(this).attr('id')+'_pulse').animate({opacity:"0", width:"40px", height:"40px", 'marginLeft':'-25px','marginTop':'-20px'},500).hide();
				}
			
	   			$(this).attr('dragging', true);
			
//	      		$("#"+$(this).attr('id')+"_overlay").hide();
	      	
	      		// If alt key is pressed when resizing then resize all childrens also
	      		// DEBUG: Tässä on bugi.. vois vähän kattoo 
	      		if(e.altKey === true)
	      		{
	      			rOptions.alsoResize = "#"+$(this).attr('id') + " > *";
	      		}

				jOptions.scroll = true;
				jOptions.scrollSensitivity = 20;
								
//				var dOptions = {};
//				dOptions.accept = function(element_id){return false;};
//				$(this).droppable(dOptions);

				// stopPropagation pitää käyttää sentakii et kaikki ko. elementin alla olevat elementit liipasee
				// myös click:in ja tää keskeyttää täksi ajaksi kaikki eventit jolloin ei niin tapahdu				
				e.stopPropagation();
			});
			
		//	e.stopPropagation();			
		}		
	});		
}		
		
jQuery.fn.teditable = function(options) 
{
	$(this).each(function()
	{
		if($(this).length > 0 && $(this).attr('id'))
		{			
			$(this).dblclick( function(e) 
			{
				
				// stopPropagation pitää käyttää sentakii et kaikki ko. elementin alla olevat elementit liipasee
				// myös click:in ja tää keskeyttää täksi ajaksi kaikki eventit jolloin ei niin tapahdu
				e.stopPropagation();
			});
		}
	});			
}		
		
function markElement(element_id)
{
	$('#'+element_id).click();
}

function UpdateToolbarElements()
{
	var treeview = "";
	var img_src = "";
	var iclass = "";
	
	//$("#toolbar_elements").append('<ul class="treeview" id="tree">');
	treeview = '<ul class="treeview" id="tree">';
	
	$("#main_container :parent.resizable").each(function()
	{
		/// DEBUG: Tähän tulee sitten turhia parentteja koska
		// se ottaa varmaan overlayn, pulsen ja wrapin mukaan jolloin se saa childeiks 3 kpl ainakin :D ..
		// Se pitää nyt selvittää miten sen tekis
		if($(this).children().length > 0)
		{
			var str_class="";
			// Parent
			if($('#'+$(this).attr('id')+" .resizable").length > 0)
			{
				str_class = "hitarea expandable-hitarea";
			}
			else
			{
				str_class = "";
			}
			
			treeview += '<li class="expandable"><div class="'+str_class+'"></div><a href="javascript:markElement(\''+$(this).attr('id')+'\')"><strong>'+$(this).attr('id')+'</strong></a><ul style="display: none;">';
		
			$('#'+$(this).attr('id')+" .resizable").each(function()
			{
				if($(this).attr('tagName') === 'IMG')
				{
					img_src = $(this).attr('src');
					iclass = 'toolbar_tree_thumbnail';
				}
				else if($(this).css('backgroundImage') !== 'none')
				{
					
					img_src = $(this).css('backgroundImage');
					/// DEBUG: url() replace pitää tehä firefoxia varten mutta tän vois tehä replace regexpillä.
					// replace tukee suoraan regularia ja sille vois antaa tiedon et otetaan ainoastaan teksti sulkujen sisältä
					// tai sitten splitillä joka tekee arrayn vaikka niin et ekassa olis url( ja tokassa sisältö ja kolmannessa )
					// tai sitten ei valitse regularissa muuta kun yhen (näinhän pysty tekee suluilla tai hakasulkeilla) ja se on se sisältö
//					img_src = img_src.replace('/(^url)\(.*?\)/i','');
					img_src = img_src.replace('url(','');
					img_src = img_src.replace(')','');

					iclass = 'toolbar_tree_thumbnail';
				}
				else
				{
					img_src = "images/element.png";
					iclass = '';
				}

				treeview += '<li><div style="position:absolute"><img style="width:10px;height:10px" class="'+iclass+'" src="'+img_src+'"/></div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:markElement(\''+$(this).attr('id')+'\')">'+$(this).attr('id')+'</a></li>';
				// Childs
	//				treeview += '<li><a href="">'+$(this).attr('id')+'</a></li>';
			});		
			// Parent close
			treeview += '</ul></li>';
		}		
	});
	treeview += '</ul>';
	
//	$("#lower_toolbar_elements").append(treeview);
	
	$('.toolbar_tree_thumbnail').hover( function () 
    {
	    $(this).css({'z-index':9999, 'borderStyle':'solid','borderWidth':'1px','borderColor':'darkgreen'});
        $(this).animate({ width: "+=40px", height: "+=40px", "marginTop": "-=20px", "marginLeft":"-=20px"}, 100);
    }, function () 
    {
    	$(this).css({'z-index':99, 'borderStyle':'none','borderWidth':'0px','borderColor':'none'});
    	$(this).animate({ width: "-=40px", height: "-=40px", "marginTop": "+=20px", "marginLeft":"+=20px"}, 100);
    });

	$("#tree").treeview({
		collapsed: true,
		animated: "medium",
		//control:"#sidetreecontrol",
		prerendered: true,
		persist: "location"
	});
}

function StartToEditElements()
{	
	$(".resizable").tresizable({parent_drag:true});

//	$(".editable").teditable();

	if(STARTED_TO_EDIT_PAGE == false)
	{	
			$("#main_container").append('<style type="text/css">.ui-resizable-handle { position: absolute; z-index: 1001; display: none; -moz-user- select: none;}.ui-resizable-box{display:block;width:8px;height:8px;}.ui-resizable-e {margin-right:-5px;right:0px;top:50%;margin-top:-5px;cursor:e-resize}.ui-resizable-w {margin-left:-13px;left:0px;top:50%;margin-top:-5px;cursor:w-resize}.ui-resizable-n {margin-left:50%;margin-top:-13px;left:-5px;cursor:n-resize}.ui-resizable-s { margin-left:50%;margin-bottom:-5px;bottom:0px;left:-5px;cursor:s-resize}.ui-resizable-sw{margin-left:-13px;margin-bottom:-5px;bottom:0px;cursor:sw-resize}.ui-resizable-se{right:0px;margin-right:-5px;margin-bottom:-5px;bottom:0px;cursor:se-resize}.ui-resizable-nw{margin-left:-13px;margin-top:-13px;top:0px;cursor:nw-resize}.ui-resizable-ne{margin-right:-5px;right:0px;margin-top:-13px;top:0px;cursor:ne-resize}</style>');

			var res_options = {};
/*			
		   	$(".ui-resizable-handle").hover( function () 
		   	{
				res_options.width = "+=4px";
				res_options.height = "+=4px";
		   		if($(this).css('marginLeft') != '0px') res_options.marginRight = "-=2px"; else res_options.marginLeft = "-=2px";
		   		if($(this).css('marginTop') != '0px') res_options.marginBottom = "-=2px"; else res_options.marginTop = "-=2px";
	       		$(this).animate(res_options,100);
      		}, function () 
      		{
				res_options.width = "-=4px";
				res_options.height = "-=4px";
		   		if($(this).css('marginLeft') != '0px') res_options.marginRight = "+=2px"; else res_options.marginLeft = "-=2px";
		   		if($(this).css('marginTop') != '0px') res_options.marginBottom = "+=2px"; else res_options.marginTop = "-=2px";
	       		$(this).animate(res_options,100);
    		});*/

		$("#main_container").css('position','absolute');
		$("#main_container").animate({top:'50px'},1000);

	    Request('function/XML/GetTemplate',"{'async':'false', 'append':'true', 'dest':'-body', 'method':'get'}","{'file':'sites/teeko2/action/app/editor/pagemap.xml'}");		
	    Request('function/XML/GetTemplate',"{'async':'false', 'append':'true', 'dest':'-body', 'method':'get'}","{'file':'sites/teeko2/action/app/editor/top_toolbar.xml'}");
	    Request('function/XML/GetTemplate',"{'async':'false', 'append':'true', 'dest':'-body', 'method':'get'}","{'file':'sites/teeko2/action/app/editor/control_panel.xml'}");
	    
	    //DEBUG: tää effects laatikko tulee sitten loppujen lopuks jostain menusta 
	    // mut nyt testin vuoks ladataan se heti!!
	    Request('function/XML/GetTemplate',"{'async':'false', 'append':'true', 'dest':'-body', 'method':'get'}","{'file':'sites/teeko2/action/app/editor/effects.xml'}");
	    
	    
	   $("#main_container").live('mouseup',function () 
       {
      		if($(global_resize_handler).length > 0)
	   			$(global_resize_handler).mouseup();
    	});
    	
		$(".ui-resizable-box").live('mouseover', function () 
  		{
  			if($(this).attr('mousedown') !== "true")
    			$(this).animate({width:"12px",height:"12px",left:"-2px",top:"-2px"},100);
	    }).live('mouseout', function ()
	   	{
			if($(this).attr('mousedown') !== "true")
		  		$(this).animate({width:"8px",height:"8px",left:"0px",top:"0px"},100);
    	}).live('mousedown', function () 
    	{
		 	global_resize_handler = $(this);
		   		
	     	$(this).attr('mousedown', "true");
	     	$(this).attr('src', "images/resize_box_click.png");
	     	$(this).animate({width:"8px",height:"8px",left:"0px",top:"0px"},100);
    	}).live('mouseup', function () 
    	{
      		global_resize_handler = false;
	     	$(this).removeAttr('mousedown');
	       	$(this).attr('src', "images/resize_box.png");
    	});

 	}
			
	STARTED_TO_EDIT_PAGE = true;
}

jQuery.fn.editElement = function()
{	
//	$(".resizable").tresizable({parent_drag:true});
//	$(".editable").teditable();
	 $(this).tresizable({parent_drag:true});
	 
	 		// DEBUG: Tääki on monessa kohtaa mutta ei sais olla ku yhessä joten joko functiona
	 		// tai sitten vaan oikeasti yhessä paikassa

	 /*
		   	$(this).find(".ui-resizable-handle").hover( function () 
		   	{
	       		$(this).animate({width:"+=4px",height:"+=4px",top:"-=2px",left:"-=2px"},100);
      		}, function () 
      		{
           		$(this).animate({width:"-=4px",height:"-=4px",top:"+=2px",left:"+=2px"},100);
    		});		 
    */
}



function GetElementClasses()
{	
	// DEBUG: Tähän pitäis sitte tehä niin et nää eri luokka metodit on kaikki eri filuissa ja
	// ajaxilla pyydetään eka kaikki erilaiset fileet esim. menubutton ja sitten ne 
	// vedetään tolla .menubutton).menubutton() ajolla
	
	var allClasses = new Array("menubutton","bclick", "oneclick");
	
	$.each(allClasses,function(i,item)
	{
		eval('$(".'+item+'").'+item+'()');
	});	
}

$.fn.menubutton = function()
{
	$(this).removeClass('menubutton');

	$(this).each(function()
	{
		var parent_id = $(this).parent().attr('id');

		$(this).attr('src_out', $(this).attr('src'));
	
    	$(this).hover(function()
    	{
	    	$(this).attr('src', $(this).attr('src_on'));
    	}, 
    	function()
    	{
    		if(!$(this).hasClass('teeko-menu-selected'))
    		{
		 	   $(this).attr('src', $(this).attr('src_out'));
		 	}
	    });
	
		$(this).bind('click', function()
		{
			$('.teeko-menu-selected').removeClass('teeko-menu-selected').mouseout();
			$(this).addClass('teeko-menu-selected').mouseover();		
		});
	});
}

$.fn.bclick = function()
{
	$(this).each(function()
	{
		if(!hash.exists())
		{
			$(this).attr('src', $(this).attr('src_on'));
			$(this).click().removeClass('bclick');
			hash.locat( $(this).attr('href') );
		}
	});
}

$.fn.oneclick = function()
{
	$('.oneclick:first').click();
	$(".oneclick").removeClass('oneclick');
}


function pathinfo (path, options) {

    var opt = '', optName='', tmp_arr = {}, cnt = 0, i=0;
    var have_basename = false, have_extension = false, have_filename = false;

    // Input defaulting & sanitation
    if (!path) {return false;}
    if (!options) {options = 'PATHINFO_ALL';}

    // Initialize binary arguments. Both the string & integer (constant) input is
    // allowed
    var OPTS = {
        'PATHINFO_DIRNAME': 1,
        'PATHINFO_BASENAME': 2,
        'PATHINFO_EXTENSION': 4,
        'PATHINFO_FILENAME': 8,
        'PATHINFO_ALL': 0
    };
    // PATHINFO_ALL sums up all previously defined PATHINFOs (could just pre-calculate)
    for (optName in OPTS) {
        OPTS.PATHINFO_ALL = OPTS.PATHINFO_ALL | OPTS[optName];
    }
    if (typeof options !== 'number') { // Allow for a single string or an array of string flags
        options = [].concat(options);
        for (i=0; i < options.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[options[i]]) {
                options = options | OPTS[options[i]];
            }
        }
    }

    // Internal Functions
    var __getExt = function (path) {
        var str  = path+'';
        var dotP = str.lastIndexOf('.')+1;
        return str.substr(dotP);
    };


    // Gather path infos
    if (options & OPTS.PATHINFO_DIRNAME) {
        tmp_arr.dirname = this.dirname(path);
    }

    if (options & OPTS.PATHINFO_BASENAME) {
        if (false === have_basename) {
            have_basename = this.basename(path);
        }
        tmp_arr.basename = have_basename;
    }

    if (options & OPTS.PATHINFO_EXTENSION) {
        if (false === have_basename) {
            have_basename = this.basename(path);
        }
        if (false === have_extension) {
            have_extension = __getExt(have_basename);
        }
        tmp_arr.extension = have_extension;
    }

    if (options & OPTS.PATHINFO_FILENAME) {
        if (false === have_basename) {
            have_basename = this.basename(path);
        }
        if (false === have_extension) {
            have_extension = __getExt(have_basename);
        }
        if (false === have_filename) {
            have_filename  = have_basename.substr(0, (have_basename.length - have_extension.length)-1);
        }

        tmp_arr.filename = have_filename;
    }


    // If array contains only 1 element: return string
    cnt = 0;
    for (opt in tmp_arr){
        cnt++;
    }
    if (cnt == 1) {
        return tmp_arr[opt];
    }

    // Return full-blown array
    return tmp_arr;
}

function basename (path, suffix) {
    var b = path.replace(/^.*[\/\\]/g, '');
    
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }
    
    return b;
}
function dirname (path) {
    return path.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, '');
}

try {
	window.addEventListener('load', GetElementClasses, false);
} catch(e) {
	window.onload = GetElementClasses;
}

