 $.fn.replaceText = function( search, replace, text_only ) {
    return this.each(function(){
      var node = this.firstChild,
        val,
        new_val,
        
        // Elements to be removed at the end.
        remove = [];
      
      // Only continue if firstChild exists.
      if ( node ) {
        
        // Loop over all childNodes.
        do {
          
          // Only process text nodes.
          if ( node.nodeType === 3 ) {
            
            // The original node value.
            val = node.nodeValue;
            
            // The new value.
            new_val = val.replace( search, replace );
            
            // Only replace text if the new value is actually different!
            if ( new_val !== val ) {
              
              if ( !text_only && /</.test( new_val ) ) {
                // The new value contains HTML, set it in a slower but far more
                // robust way.
                $(node).before( new_val );
                
                // Don't remove the node yet, or the loop will lose its place.
                remove.push( node );
              } else {
                // The new value contains no HTML, so it can be set in this
                // very fast, simple way.
                node.nodeValue = new_val;
              }
            }
          }
          
        } while ( node = node.nextSibling );
      }
      
      // Time to remove those elements!
      remove.length && $(remove).remove();
    });
  };  

  
var global = {
	data : {},
	get: function(key)
	{
		return this.data[key];
	},
	put: function(key, value)
	{
		this.data[key] = value;
	},
	call: function()
	{
	}	
};
/*
function updateJSONInput(strkey, strvalue, dest)
{
	var json = eval('('+$(dest).val()+')');
	
	var skey = $(strkey).val();
	var svalue = $(strvalue).val();
	
	json.push({"type":skey,"value":svalue});
	
	$(dest).val(JSON.stringify(json));
}
*/
function EmailProtection()
{
	$(":contains('(at)')").replaceText(/\(at\)/g,"@").replaceText(/\(dot\)/g,".");
	$(":contains('(-at)')").replaceText(/\(-at\)/g,"@").replaceText(/\(-dot\)/g,".");

	$("a[href*='(-at)']").each(function()
	{ 
		$(this).attr('href',$(this).attr('href').replace(/\(-at\)/g,"@").replace(/\(-dot\)/g,"."));
	});
};
/*
			function scrollStart ( $scroll , opt ) {
				var pos = -( $scroll.width() - $scroll.parents( "div:eq(0)" ).width() ) + $scroll.children( ":last" ).width();
				var spd = opt.speed - ( ( $scroll.children( ":last" ).width() - ( Math.abs ( parseInt( $scroll.css( "marginLeft" ) ) ) - Math.abs ( pos ) ) ) * ( opt.speed / $scroll.children( ":last" ).width() ) );
				
				$scroll.animate(
					{marginLeft: ( pos || "0" ) + "px", marginTop: ( tos || "0" ) + "px"}
					, spd
					, "linear"
					, function () {
								$scroll.append( $( this ).children( ":eq(0)" ) );
								$scroll.css( "marginLeft" , "0px" );
						scrollStart( $scroll , opt );
					}
				);
				}*/
				
				
$.fn.infiniteScroll = function()
{
	var $$ = $(this);
	
	setInterval( function() {
		$$.animate({left:- ($$.width() - $$.parent().width())}, 500000);
	}, 100);
	
	//$$.scrollTo({left:'+=100'},1000);
	//$$.animate({left:- ($$.width() - $$.parent().width())}, 5000, function() { /*$(this).clone().appendTo($(this).parent()); $(this).animate({left:'-9633px'}, 1000); */});
}

$.fn.grid = function(method, parms)
{
        //var $$ = $('#site_editor');
        var $$ = $(this);
        
        if(global.get('isGrid') == 0) return false;
        
        /// Create GRID
        if(method == 'show' || method == 'refresh')
        {
        	
        	if($$.find("[teeko-editor-element-type='grid']").length > 0 && method == 'show')
        	{
        		//$('body').find("[teeko-editor-element-type='grid']").show();
        		$$.find("[teeko-editor-element-type='grid']").show();
        	}
        	else
        	{   
        		$$.find("[teeko-editor-element-type='grid']").remove();
        		     		
   				var sY = 73;
   				var sX = 40;
   				var pageHeight = parseFloat($(document).height()) - sY;
   				var pageWidth = parseFloat($(document).width()) - sX;
   				
   				var yStep = global.get('grid');
   				var xStep = global.get('grid');
   				
   				if(!yStep) yStep = 10;
   				if(!xStep) xStep = 10;

				var zindex = '998';
				
				if(typeof parms !== 'undefined')
				{
					if(typeof parms.zindex !== 'undefined') zindex = parms.zindex;
				}

   				var yLines = pageHeight / yStep;
   				
   				$$.append("<div teeko-editor-element-type='grid' style='z-index:"+zindex+";left:0px;top:0px;border:1px inset #000;width:100%;height:100%;position:fixed;opacity:.1'></div>");
   				
   				var col = '#FFF';
   				
   				for (i = 0; i <= yLines - 1; i++) {
   					col = (i % 2 == 0) ? '#FFF' : '#4F4F4F';
   					
					$$.find("[teeko-editor-element-type='grid']").append("<div class='horiz' style='left:0px;top:"+sY+"px;border:1px inset "+col+";width:100%;height:0px;position:absolute'></div>");
					sY += yStep;
				}
   				
   				var xLines = pageWidth / xStep;

   				for (i = 0; i <= xLines - 1; i++) {
      				col = (i % 2 == 0) ? '#FFF' : '#4F4F4F';

					$$.find("[teeko-editor-element-type='grid']").append("<div class='vert' style='top:0px;left:"+sX+"px;border:1px inset "+col+";height:100%;width:0px;position:absolute;'></div>");
					sX += xStep;
				}
        	}
        }
        else if(method == 'hide')
        {
        	$$.find("[teeko-editor-element-type='grid']").hide();
        }
};
/*
$.fn.tooltip = function(options)
{
	$(this).live('mouseout', function() {
		$('body').find('#tooltip').fadeOut(200, function() {$(this).remove();});
		//$('#main_container').find('#tooltip').fadeOut(200, function() {$(this).remove();});
	}).live('mouseover', function() {
			var offset = $(this).offset();
			//$('#main_container > #tooltip').remove();
			$('body > #tooltip').remove();
			//if($('#main_container').find('#tooltip').length == 0)
			if($('body').find('#tooltip').length == 0)
			{
				//$('#main_container').append("<div id='tooltip' style='display:none;z-index:99;background:url(images/tooltip.png);position:absolute;width:166px;height:126px;text-align:center;top:"+(parseInt(offset.top)-parseInt($(this).css('height')))+"px;left:"+(parseInt(offset.left)+10)+"px;'><span style='position:absolute;left:8px;width:150px;'>"+$(this).attr('tooltip')+"</span></div>").find('#tooltip').show('bounce',10);
				$('body').append("<div id='tooltip' style='display:none;z-index:99;background:url(images/tooltip.png);position:absolute;width:166px;height:126px;text-align:center;top:"+(parseInt(offset.top)-parseInt($(this).css('height')))+"px;left:"+(parseInt(offset.left)+10)+"px;'><span style='position:absolute;left:8px;width:150px;'>"+$(this).attr('tooltip')+"</span></div>").find('#tooltip').show('bounce',10);
			}
	});
};

$('.teeko-tooltip').tooltip();
*/
$.fn.overlay = function(cb)
{
	//if($("#main_container").find('#editor-overlay').length > 0)
	if($("body").find('#editor-overlay').length > 0)
	{
		//$("#main_container").find('#editor-overlay').fadeOut(200, function() {$(this).remove();});
		$("#body").find('#editor-overlay').fadeOut(200, function() {$(this).remove();});
	}
	else
	{
		//$("#main_container").append('<div id="editor-overlay"></div>');
		$("body").append('<div id="editor-overlay"></div>');

		//$("#main_container").find('#editor-overlay').css({
		$("body").find('#editor-overlay').css({
			'background-color' 	: '#000',
			'display'			: 'block',
			'width'				: '100%',
			'left'				: '0',
			'top'				: '0',
			'height'			: '100%',
			'z-index'			: '98',
			'position'			: 'fixed',
			'opacity'			: '0.5',
			'filter'			: 'alpha(opacity=50)'
		}).fadeIn(200, cb);
	}
};

$.fn.scale = function(parms)
{
	if(!parms.ease) parms.ease = 'easeOutBack';
	
    $(this).hover(
      function () {
      	parms.cwidth = $(this).width();
      	parms.cheight = $(this).height();
      // Easing methods: easeOutElastic, easeOutBack, linear, easeOutQuart, 
//      	$(this).data('zindex', $(this).css('z-index') == 'auto' ? 1 : $(this).css('z-index')).css('z-index', 10).addClass('teeko-editor-hover').animate({width:"+="+parms.width,height:"+="+parms.height,marginTop:"-="+(parms.height / 2),marginLeft:"-="+(parms.width / 2)},parms.speed,parms.ease, function() { /*if($(this).hasClass('teeko-editor-hover')) $(this).rate();*/});	
		$(this).parent().find('.gallery-title').css('z-index', 10);	
      	$(this).data('zindex', $(this).css('z-index') == 'auto' ? 1 : $(this).css('z-index')).css('z-index', 10).animate({width:parms.width,height:parms.height,marginTop:((parms.cheight - parms.height) / 2),marginLeft:((parms.cwidth - parms.width) / 2)},{duration:parms.speed,easing:parms.ease,queue:false}, function() { /*if($(this).hasClass('teeko-editor-hover')) $(this).rate();*/});
      }, 
      function () {
      	//$(this).hideRate();
		$(this).parent().find('.gallery-title').css('z-index', 9);
      	$(this).css('z-index',9).animate({width:parms.cwidth,height:parms.cheight,marginTop:0,marginLeft:0},{duration:parms.speed,easing:parms.ease,queue:false}, function() { $(this).css('z-index', $(this).data('zindex')); });
      }
    );
};
jQuery.fn.clearForm = function() 
{
    $(this).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            	break;
            case 'select-one':
            	break;
            case 'text':
            case 'textarea':
                $(this).val('');
                $(this).removeClass('error');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
};	

/// Image preloader class
var ImagePreloader = {
	status:		false,
	load: function()
	{
	},
	unload: function()
	{
	},
	init: function() {	
	}
};

function CreateImageFromElement(destination, fnCallback, efnCallback, parms)
{
	var elements = {};

	if($(destination).find('*').length == 0)
	{
		if(typeof efnCallback == 'function') efnCallback.call();
		return;
	}

	if(typeof parms == 'undefined') var parms = {};
	
	if(typeof parms.width == 'undefined') parms.width = $(destination).width();
	if(typeof parms.height == 'undefined') parms.height = $(destination).height();
	if(typeof parms.bgcolor == 'undefined') parms.bgcolor = '#000';

	if(typeof parms.width == 'undefined') parms.width = $(destination).width();
	if(typeof parms.height == 'undefined') parms.height = $(destination).height();	
	
	elements[0] = {width: parms.width, height: parms.height, bgcolor:parms.bgcolor};

	$.each( $(destination).not('#teeko-uploader-progress').find('img'), function(i,v) {
		if(typeof parms.ewidth == 'undefined') parms.ewidth = $(v).width();
		if(typeof parms.eheight == 'undefined') parms.eheight = parseInt($(v).css('height'));

		elements[i+1] = {rotation: $(v).attr('rotation'), width:parms.ewidth, height:parms.eheight, left:$(v).css('left'), top:$(v).css('top'), src:$(v).attr('src')}
		parms.ewidth = undefined;
		parms.eheight = undefined;
		
	});
	
	Request('function/file/CombineImg', {callback: fnCallback }, elements);
}


function Calculate(parms, dest, endtext)
{
	//var list = parms.split('*');

	var calstr = "";
	/*
	$.each(list,function(i,item) 
	{
		if(item[0] == '#') calstr += "$('"+item+"').val()*"; else calstr += parseFloat(item) + "*";
	});
	
	calstr = calstr.slice(0, -1);
	*/
	parms = parms.replace(/(#\w+)/g, "$('$1').val()");

	// Tähän parmsiin pitää tehä vielä sitten jotain tarkistuksia ettei kukaan voi käyttää tätä väärin 
	// kun noita lukemia voi ite kirjottaa niin sittehän sinne vois kirjottaa javascriptiäkin?
	var sum = Math.round(eval(parms));

	$(dest).text(sum+' '+endtext);
}

function ArraySearch(needle, haystack)
{
	for(key in haystack)
	{
		var value = haystack[key];
	
   		if(value == needle) 
   		{
   			return true;
   		}
	}
	return false;
}

$.fn.preloader = function(fn)
{
	if (typeof preloaded_images == 'undefined') {
		preloaded_images = [];
	}
	
	var src = $(this).attr('src');

	//if(preloaded_images.indexOf(src) !== -1)
	if(ArraySearch(src, preloaded_images) !== false)
	{
		fn.call();	
	}
	else
	{
		var img = new Image();
	
		$(img).load(function()
		{	
			preloaded_images.push(src);
			fn.call();
		})
		.error(function()
		{
			preloaded_images.push(src);
			fn.call();
		})
		.attr('src', src);
	}
	
	return $(this);
};


/// Page Preloader class
var preloader = {
	PRELOADER_TIMEOUT: 300,
	interval:	false,
	obj:		false,
	status:		false,
	show: function()
	{
		this.obj.css({marginLeft:'-175px',opacity:0}).show().animate({marginLeft:'-70px','opacity':1},400);
	},
	load: function()
	{
		var $$ = $('#loading_animation');
		
		if($$.length > 0 && this.status === false)
		{
			this.obj = $$;
			this.status = true;
		 	this.interval = setTimeout('preloader.show()', this.PRELOADER_TIMEOUT);
		}						
	},
	unload: function()
	{
		var preloader = $('#loading_animation');
		if(preloader.length > 0)
		{
			clearTimeout(this.interval);
			
			this.interval = false;
			
			if(this.status === true)
			{
				this.status = false;
				preloader.fadeOut(500, function() { $(this).hide();});
			}
		}
	},
	init: function() {	
	}
};

var editor = {
	status:	false,
	layer: '#site_editor',
	exists: function()
	{
		return ( $(this.layer).length > 0 ) ? true : false;
	},
	load: function()
	{
	},
	target: function()
	{
		return this.layer;
	},
	init: function() 
	{	
		$(document).find('a').each( function() 
		{
			/// Unwrapataan kaikki hrefit sentakia ettei teekossa kun painetaan linkkeihin niin se siirtyis 
			/// fyysisesti niihin vaan ajax lataisi ne.
			//$(this).find(':eq(0)').unwrap();
			if($(this).attr('href')!=='#') $(this).find(':eq(0)').unwrap();
			//$(this).attr('href','');
			//$(this).find('a').attr('href','#');
		});			
	}
};


/// Custom selectoreitahan vois tehä ihan sellasiakin et #site_editor:wrapper, #site_editor:element-selected

jQuery.fn.animateBackground = function(direct, parms)
{
	var $$ = $(this);

	if(parms.speed == 0) parms.speed = 1;
	
	if(!$$.data('oldcolor')) $$.data('oldcolor', $$.css('color'));
	if(!$$.data('oldFontWeight')) $$.data('oldFontWeight', $$.css('font-weight'));
	if(!$$.data('oldTextDecoration')) $$.data('oldTextDecoration', $$.css('text-decoration'));

	if(direct == 1)
	{
		$$.css('color',parms.hcolor);
		$$.css('font-weight',parms.fontWeight);
		$$.css('text-decoration',parms.textDecoration);

		if(typeof $$.backgroundImage() !== 'undefined' && $$.data('height') > 0) $(this).stop().animate({backgroundPosition:"0px -"+$$.data('height')+"px"}, {duration:parms.speed});
	}
	else
	{
		$$.css('color',$$.data('oldcolor'));
		$$.css('font-weight',$$.data('oldFontWeight'));
		$$.css('text-decoration',$$.data('oldTextDecoration'));
		if($$.data('height') > 0) $(this).stop().animate({backgroundPosition:"0px 0px"}, {duration:parms.speed});			
	}
};

jQuery.fn.preloadBackground = function(direct, parms)
{
	var el = $(this);

	if(!el.data('height') && typeof el.backgroundImage() !== 'undefined')
	{
		var image = new Image();

		$(image).load( function()
		{
			el.data('height', this.height - parseInt(el.css('height')));
			el.animateBackground(direct, parms);
		}).attr('src', el.backgroundImage());
	}
	else el.animateBackground(direct, parms);
};

/// Custom Selectors ------------------------------------
$.extend($.expr[':'],{
    backgroundImage: function(a) {
        return $(a).css('background-image') !== 'none';
    },
    wrapper: function(a) {
        return $(a).data('teeko-wrapper') === 'true';
    },
    autoOverflow: function(a) {
    // ei käytössä
        return $(a).css('overflow') === 'auto';
    },
    fullSize: function(a) {
    // Ei käytössä
        return $(a).css('width') === '100%';
    }
});

$.fn.extend({_animate: $.fn.animate,_css: $.fn.css});

jQuery.fn.extend
({
    removeCSS: function(cssName) {
        return this.each(function() {

            return $(this).attr('style',

            jQuery.grep($(this).attr('style').split(";"),
                    function(curCssName) {
                        if (!curCssName.match(new RegExp(cssName + "(-.+)?:"), "mi"))
                            return curCssName;
                    }).join(";"));
        });
    }
});

$.extend($, {
    inJSON: function(json, key){
        var hit, hits = [];
        $.each(json, function(k,v){
            if (k === key)
                hits.push(v);
            if (typeof(v) === "string"){
                return true;
            } else if ($.isArray(v) || $.isPlainObject(v)) {
                var r = $.inJSON(v, key);
                if (r.length > 0)
                    hits = hits.concat(r);
            }
        });
        return hits;
    }
});


var parent_showed = false;

jQuery.fn.uniqueByTag = function(tag) 
{

	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x][tag]==this[i][tag])
			{
				this.splice(x, 1);
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	/*
	$.each(this,function(i,item) 
	{
		console.log(item['src']);
		$.each(this,function(i2,item2) 
		{
			if(item[tag] == item2[tag] && )
			{
				//this.splice(i, 1);
			}
		});
	});*/
};
/*
jQuery.fn.css = function(parm, value)
{
	// Lets create IE fix and add alpha filter if opacity is changed!
	if(parm.opacity) parm.filter = 'alpha(opacity = '+ parm.opacity * 100 +')';

	if(value)
		return $(this)._css(parm, value);
	else
		return $(this)._css(parm);	
}
*/

jQuery.fn.preload = function()
{
	var $$ = $(this);

	$$.find('img,div:backgroundImage').each(function()
	{
		var src = $(this).attr('src');			
		if(src === undefined) src = $(this).backgroundImage();

		var img = new Image();

		$$.data('teeko-editor-preloading',{});
		
		$(img).load(function()
		{
			$$.data('teeko-editor-preloading').loaded++;
			if($$.data('teeko-editor-preloading').loaded == $$.data('teeko-editor-preloading').images) setTimeout( function() {$$.show().data('teeko-editor-preloading',false);},10);
		})
		.error(function()
		{
		    // If error then continue cause otherwise picture doesnt show anywhere
		    // if element has 5 pictures and 4 pictures is loaded then no animation occurs 
			$$.data('teeko-editor-preloading').loaded++;
			if($$.data('teeko-editor-preloading').loaded == $$.data('teeko-editor-preloading').images) setTimeout( function() {$$.show().data('teeko-editor-preloading',false);},10);
		})
		.attr('src', src).hide();
	});
}
/*
function preload()
{
	$('#main_container').preload();
}
*/
/*
try {
	window.addEventListener('load', preload, false);
} catch(e) {
	window.onload = preload;
}
*/
/*
jQuery.fn.animate = function(parm, speed, cb)
{
	// Tähänhän me voidaan hakea tieto esim. tietokannasta!! tai sitten
	// ihan vaan templaten alussa on esim. <dontanimate></dontanimate>
	var dont_animate = false;

	var el = $(this);
	var imgs = el.find('img,div:backgroundImage');

	// TÄÄ HEITTÄÄ VIRHETTÄ ETTEI TOIMI SAFARILLA!!! 
	// DEBUG: OTETAAN NÄÄ UNIIKKI JUTUT VIELÄ POIS MUTTA NE ON LISÄTTÄVÄ MAHD PIAN KOSKA MUUTEN
	// TÄSSÄ KÄYDÄÄN TURHIA JUTTUJA LÄPI!!!	
		//	imgs.uniqueByTag('src');	
		//	imgs.uniqueByTag('background-image');

	/// DEBUG: tähän vois myös tehä jonku sellasen et ei sellasii enää tarvi ladata mitkä olis jo latautunu
	// mutta ei oo ladattu tällä.. sillohan teeko-editor-preloading === undefined vaikka ne olis jo ladattu
	// ja ei niit uusiks kannata ladata.. mutta mistä se katotaan?!? preloadataanko loppujen lopuks aivan kaikki
	// graffa et saadaan merkatuks et nyt on preloadattu!!?!?
	
	
	/// DEBUG: Tehty nyt tohon toi et site_editor elementti pitää löytyä ennenku käytetään animate
	/// preloadingia.. se johtuu IE bugista hellstattoo sivuilla.. eli menu animaatiot ei ekalla clikkauksella
	/// tehty ollenkaan.. ja se johtu tästä kun jostain syystä se ei preloadannu niitä	
	if( el.data('teeko-editor-preloading') === undefined && imgs.length > 1 && editor.exists() === true)
	{
		el.data('teeko-editor-preloading', {});
		
		if(el.attr('tagName') === 'IMG' || el.css('background-image') !== 'none') imgs.push(el);
		
		imgs.each(function()
		{
			var src = $(this).attr('src');			
			if(src === undefined) src = $(this).backgroundImage();

			var img = new Image();
			
			$(img).load(function()
			{
				el.data('teeko-editor-preloading').loaded++;
				if(el.data('teeko-editor-preloading').loaded == el.data('teeko-editor-preloading').images) setTimeout( function() {return el._animate(parm, speed, cb).data('teeko-editor-preloading',false);},10);
			})
			.error(function()
			{
			    // If error then continue cause otherwise picture doesnt show anywhere
			    // if element has 5 pictures and 4 pictures is loaded then no animation occurs 
			    if(el.data('teeko-editor-preloading') !== undefined)
			    {
					el.data('teeko-editor-preloading').loaded++;
					if(el.data('teeko-editor-preloading').loaded == el.data('teeko-editor-preloading').images) setTimeout( function() {return el._animate(parm, speed, cb).data('teeko-editor-preloading',false);},10);
				}
			})
			.attr('src', src);
		});
		
		el.data('teeko-editor-preloading', { status: true, loaded: 0, images: imgs.length });
	}
	else
	{
//		if(parm.opacity) parm.filter = 'alpha(opacity = '+parm.opacity * 100+')';
			
		if(dont_animate)
			el.css(parm);
		else
			return el._animate(parm, speed, cb);
	}
}
*/
jQuery.fn.backgroundImage = function()
{
	//var regex = new RegExp("url\\('?([^']*)'?\\)", 'gi');
	//var match = regex.exec( $(this).css('background-image') );

	//if(match !== null) return match[match.index+1];
	if($(this).css('backgroundImage') !== undefined && $(this).css('backgroundImage') !== 'none' && $(this).css('backgroundImage') !== null)
	{
		/// DEBUG: replace('"','') on vain ja ainoastaan IE Bugi.. se laittaa background-image url('') sisään hipsukat
		// jolloin css ei ymmärrä sitä kuvaa
		return $(this).css('backgroundImage').replace(/^url|[\(\)]/g, '').replace('"','').replace('"','');
	}
};

function validation_success(data)
{
	if(data.value === null)
	{
		alert('Check username or password!');
	}
	else
	{
		location.href = data.value;
	}
}

function validation_success2(data, act)
{
	if(data.status == false)
	{
		//alert('Check username or password!');
		Request('app/main/main/alert', {method:'get', append:'true'});
	}
	else
		Request(act, {method:'get'});
}

jQuery.fn.validation = function(act)
{
	$(this).validate(
	{
   		submitHandler: function(form) 
   		{
   			if($(form).attr('function'))
   			{
   				if($(form).attr('function').substr(0,4) == 'http')
   				{
   					$.ajax({
   						url: $(form).attr('function'),
   						data: {userName: "'" + $(form).find('#uid').attr('value') + "'", password: "'" + $(form).find('#pwd').attr('value') + "'", redirectUrlAfterLogin: "''"},
   						dataType: "jsonp",
   						success: function(data)
   						{
   							if (typeof (data) == "undefined" || data == null) {
                    			return;
                			}
                			
               				var result = data.d;
                			if (typeof (result) == "undefined" || result == null) {
                				$('#credentials_failed').fadeIn().delay(2000).fadeOut();
                				return;
  			                }
  			                
  			                window.location = result;
   						}
   					});
   				}
   				else Request($(form).attr('function'), {callback:'validation_success(data)', method:'post'},  {userName: $(form).find('#uid').attr('value'), password:  $(form).find('#pwd').attr('value')});
   			}
   			else if($(form).attr('function2'))
   			{
	   			// Clear all watermarked input boxes!!
	   			$(form).find('.watermark').attr('value','');
	   			
   				Request($(form).attr('function2'), {callback:'validation_success2(data,"'+act+'")', method:'get'}, $(form).attr('id'));
   			}
			else if($(form).attr('enctype') == 'multipart/form-data')
			{
				var status = $(form).uploader();
				
				// If enctype is multipart then form has file uploads
				//$('body').append("<div id='teeko-uploader-status' class='roundborders dropshadow' style='z-index:999999 !important;position:fixed;left:10px;top:10px;background-color:white;color:red;height:30px;width:200px;text-align:center;'>Tiedostoja lähetetään! Älä sulje selainta..</div>");
				
				if(status.progress == 0) $('body').append("<div id='teeko-uploader-status' class='roundborders dropshadow' style='z-index:999999 !important;position:fixed;left:10px;top:10px;background-color:white;color:red;height:30px;width:200px;text-align:center;'>Tiedostoja lähetetään! Älä sulje selainta..</div>");
			
				if(act) $(form).find('[teeko-element-type=button]').attr('disabled','disabled');
				form.submit();
				
				if($(form).attr('callback')) 
				{
					$(form).uploadercallback( function(data) { eval($(form).attr('callback')) } );
					//alert($(form).attr('callback'));
				}
				else
				{
					$(form).uploadercallback( function(data) {
						$('body').find('#teeko-uploader-status').fadeOut( function() {$(this).remove();});
					
						if($(form).attr('mailto')) 
						{
							Request('function/messages/email', { callback: function() {Request(act, {method:'get'})} , method:'post' }, $(form).attr('id'), [{'name':'settings.mailto','value':$(form).attr('mailto')},{'name':'settings.formtype','value':$(form).attr('formtype')},{'name':'settings.language','value':$(form).attr('language')},eval(data)]);
						}
						else if(act)
						{
							Request(act, {method:'post'}, $(form).attr('id'), eval(data));
						}
					});
				}
			}
   			else if(!act)
   			{
   				if($(form).attr('acceptCharset')) document.charset = $(form).attr('acceptCharset');
   				form.submit();
   			}
   			else if($(form).attr('shoppingcart'))
   			{
				Request('function/messages/emailshoppingcart', {callback: function() {Request(act, {method:'get'})} , method:'post'}, $(form).attr('id'), [{'name':'settings.mailto','value':$(form).attr('mailto')},{'name':'settings.formtype','value':$(form).attr('formtype')},{'name':'settings.language','value':$(form).attr('language')}]);
			}
   			else if($(form).attr('mailto'))
   			{
				Request('function/messages/email', {callback: function() {Request(act, {method:'get'})} , method:'post'}, $(form).attr('id'), [{'name':'settings.mailto','value':$(form).attr('mailto')},{'name':'settings.formtype','value':$(form).attr('formtype')},{'name':'settings.language','value':$(form).attr('language')}]);
			}
   			else if($(form).attr('sendto'))
   			{
				Request('function/messages/sendto', {callback: function() {Request(act, {method:'get'})} , method:'post'}, $(form).attr('id'), [{'name':'settings.oid','value':$(form).attr('oid')},{'name':'settings.sendto','value':$(form).attr('sendto')}]);
			}
			else
				Request(act, {method:'get'}, $(form).attr('id'));
   		},
   		errorPlacement: function(error, element) 
   		{
	   		
   			if($(element).length > 0)
   			{
   				if($(element.attr("error")).length > 0) $(element.attr("error")).show();

//   					var $$ = $(element).find('+ div');
   				
//	 	  				$$.show();
	   			/*
   				if($(element).attr('errorClass') !== "")   			
	     			$(element).addClass($(element).attr('errorClass'));
   			*/
   				$(element).keyup(function() 
   				{/*
	   				if($(element).attr('errorClass') !== "") 
					    $(element).removeClass($(element).attr('errorClass'));
				   */ 
	   				if($(element.attr("error")).length > 0) $(element.attr("error")).hide();
	   				
	   				//	$$.hide();   		
   				});
   			}
		}
   	});
}

jQuery.fn.getattr = function(attr, pos, sum) 
{
	var value = $(this).css(attr);
	if(sum > 0)
	{
		value = parseFloat(value.replace('px',''));
		
		if(pos == '-') value = value - sum;
		if(pos == '+') value = value + sum;
		
		value = value +'px';
	}

	return value;
}
/*
jQuery.fn.teeko_effects_show = function(element_id) 
{
	var parent_id = $(this).parent().attr('id');
	if(parent_id == element_id)
	{
		parent_id = $(this).attr('id');
	}

	parent_showed = parent_id;
	
	if( $("#element_hider").length == 0 )
	{
		$("#main_container").append("<style type='text/css'>#element_hider{text-align:center;margin-left:-500px;cursor:pointer;color:white;background-color:red;position:fixed;z-index:9999;left:0px;top:50px;width:200px;height:40px;opacity:0.5}</style><div id='element_hider'>Hävitit elementit. Paina tästä jos haluat ne takaisin</div>");
		
	    $("#element_hider").hover(
    	  function () {
        	$(this).animate({opacity:1});
      	}, 
      	function () {
        	$(this).animate({opacity:0.5});
      		}
    	);
    		
		$("#element_hider").click( function(e) 
		{
			showed = false;
			$(this).teeko_effects_hide('background');
			e.stopPropagation();
		});
	}

	$("#element_hider").animate( {marginLeft:'+=500px'}, 400 );
				
	$("#"+element_id+" .resizable:not(#"+parent_id+"):not(#"+parent_id+" *)").animate({marginLeft:'-=2000px',marginTop:'-=1000px'},1000);
}

jQuery.fn.teeko_effects_hide = function(element_id) 
{
	$("#element_hider").animate( {marginLeft:'-=500px'}, 400 );
	
	parent_id = parent_showed;
	parent_showed = false;
	$("#"+element_id+" .resizable:not(#"+parent_id+"):not(#"+parent_id+" *)").animate({marginLeft:'+=2000px',marginTop:'+=1000px'},1000);		
}
*/
/**
* Teeko Framework Javascript class
*
* @copyright (C) 2009 Webisti Oy. All rights reserved
* @version 1.0
* @author Tomi Tuovinen <tomi.tuovinen@webisti.fi>
*/

function AddBookmark()
{
	var title = document.title;

	var pairs = location.href.split( "#" );
	var url = pairs[0];
	 
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; 
	}	
}

function getUnixTimestamp()
{
	return Math.round(new Date().getTime() / 1000);
}
  
function addslashes(str) 
{
	if(str)
	{
		str=str.replace(/\\/g,'\\\\');
		str=str.replace(/\'/g,'\\\'');
		str=str.replace(/\"/g,'\\"');
		str=str.replace(/\0/g,'\\0');
		return str;
	}
}

function stripslashes(str) 
{
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}

function Error(errortype, efunction, edescription)
{
	var ErrorArr = {};
	
	ErrorArr.scripttype = 'JAVASCRIPT'; // 1=Javascript in Database errorhandler_scripttypes
	ErrorArr.errortype = errortype; // Database errorhandler_errortypes
	ErrorArr.file = ''; // Tähän tulee file missä errori on tapahtunut.. miten sen sais automaattisesti?
	ErrorArr.efunction = efunction;
	ErrorArr.description = edescription;
	ErrorArr.trace = ''; // PHP:llä saadaan mukavasti Trace mut mites javascriptillä?!?
	
//	Request('function/error/SetError', "{'method':'get'}", ErrorArr);
}

function CreateNewElements(direction)
{   
	$('#background *').animate({left:'-300px'},300, 'linear', function()
	{
		$('#background *').hide();
		
		Request('function/XML/GetElement',"{'async':false, 'append':'true', 'dest':'background', 'method':'get'}","{'xml':'&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;template id=&quot;Button&quot;&gt; &lt;img&gt;&lt;attribute class=&quot;resizable&quot;/&gt;&lt;attribute src=&quot;sites/ilmoitustaulu/images/postit/postit_1_blue_2.png&quot;/&gt;&lt;css top=&quot;50px&quot;/&gt;&lt;css z-index=&quot;20&quot;/&gt;&lt;css right=&quot;-300px&quot;/&gt;&lt;css position=&quot;absolute&quot;/&gt;&lt;css width=&quot;100px&quot;/&gt;&lt;css height=&quot;100px&quot;/&gt;&lt;/img&gt; &lt;/template&gt;'}");
		Request('function/XML/GetElement',"{'async':false, 'append':'true', 'dest':'background', 'method':'get'}","{'xml':'&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;template id=&quot;Button&quot;&gt; &lt;img&gt;&lt;attribute class=&quot;resizable&quot;/&gt;&lt;attribute src=&quot;sites/ilmoitustaulu/images/postit/postit_2_green_2.png&quot;/&gt;&lt;css top=&quot;400px&quot;/&gt;&lt;css z-index=&quot;20&quot;/&gt;&lt;css right=&quot;-300px&quot;/&gt;&lt;css position=&quot;absolute&quot;/&gt;&lt;css width=&quot;100px&quot;/&gt;&lt;css height=&quot;100px&quot;/&gt;&lt;/img&gt; &lt;/template&gt;'}");
		Request('function/XML/GetElement',"{'async':false, 'append':'true', 'dest':'background', 'method':'get'}","{'xml':'&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;template id=&quot;Button&quot;&gt; &lt;img&gt;&lt;attribute class=&quot;resizable&quot;/&gt;&lt;attribute src=&quot;sites/ilmoitustaulu/images/polaroid/polaroid1.png&quot;/&gt;&lt;css top=&quot;80px&quot;/&gt;&lt;css z-index=&quot;20&quot;/&gt;&lt;css left=&quot;-300px&quot;/&gt;&lt;css position=&quot;absolute&quot;/&gt;&lt;css width=&quot;100px&quot;/&gt;&lt;css height=&quot;100px&quot;/&gt;&lt;/img&gt; &lt;/template&gt;'}");
		
		$('#background *').animate({right:'300px'},300);
	} );	
}

function CheckSiteLogin(json_func_settings, element)
{
	var onErrorFunction = json_func_settings['onError'];
	var onSuccessFunction = json_func_settings['onSuccess'];
		
	var XHR = Request("function/db/CheckLogin", '{method:"get","async":"false"}', element);
	
	try
	{
		if (XHR.status == 200)
		{
			var data = XHR.responseText;
		
			if(dest_id && data == 'true')
			{
				if(onSuccessFunction)
				{
					//Request(act,'{dest:"'+dest_id+'", method:"post"}');
					eval(onSuccessFunction);
				}
				
				return true;
			}
			else
			{
				if(onErrorFunction)
				{
					//Request(act,'{dest:"'+dest_id+'", method:"post"}');
					eval(onErrorFunction);
				}
				
				return false;			
			}
		}
		else
		{}
	}
	catch(ex) {}
}

function include(filename)
{
	var head = document.getElementsByTagName('head')[0];
	
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	
	// DEBUG: tässä pitäis tarkistaa onko filenamessa jotain ja palauttaa true tai false
	// niin että GetElementClasses.js luokassa ei yritetä ees tehä uutta luokkaa jos siinä ei oo 
	// tiedostoa olemassa
	head.appendChild(script);
	
	return true;
}

