﻿var TextResizeDetector = function() { 
    var el  = null;
	var iIntervalDelay  = 200;
	var iInterval = null;
	var iCurrSize = -1;
	var iBase = -1;
 	var aListeners = [];
 	var createControlElement = function() {
	 	el = document.createElement('span');
		el.id='textResizeControl';
		el.innerHTML='&nbsp;';
		el.style.position="absolute";
		el.style.left="-9999px";
		var elC = document.getElementById(TextResizeDetector.TARGET_ELEMENT_ID);
		// insert before firstChild
		if (elC)
			elC.insertBefore(el,elC.firstChild);
		iBase = iCurrSize = TextResizeDetector.getSize();
 	};

 	function _stopDetector() {
		window.clearInterval(iInterval);
		iInterval=null;
	};
	function _startDetector() {
		if (!iInterval) {
			iInterval = window.setInterval('TextResizeDetector.detect()',iIntervalDelay);
		}
	};
 	
 	 function _detect() {
 		var iNewSize = TextResizeDetector.getSize();
		
 		if(iNewSize!== iCurrSize) {
			for (var 	i=0;i <aListeners.length;i++) {
				aListnr = aListeners[i];
				var oArgs = {  iBase: iBase,iDelta:((iCurrSize!=-1) ? iNewSize - iCurrSize + 'px' : "0px"),iSize:iCurrSize = iNewSize};
				if (!aListnr.obj) {
					aListnr.fn('textSizeChanged',[oArgs]);
				}
				else  {
					aListnr.fn.apply(aListnr.obj,['textSizeChanged',[oArgs]]);
				}
			}

 		}
 		return iCurrSize;
 	};
	var onAvailable = function() {
		
		if (!TextResizeDetector.onAvailableCount_i ) {
			TextResizeDetector.onAvailableCount_i =0;
		}

		if (document.getElementById(TextResizeDetector.TARGET_ELEMENT_ID)) {
			TextResizeDetector.init();
			if (TextResizeDetector.USER_INIT_FUNC){
				TextResizeDetector.USER_INIT_FUNC();
			}
			TextResizeDetector.onAvailableCount_i = null;
		}
		else {
			if (TextResizeDetector.onAvailableCount_i<600) {
	  	 	    TextResizeDetector.onAvailableCount_i++;
				setTimeout(onAvailable,200)
			}
		}
	};
	setTimeout(onAvailable,500);

 	return {
		 	/*
		 	 * Initializes the detector
		 	 * 
		 	 * @param {String} sId The id of the element in which to create the control element
		 	 */
		 	init: function() {
		 		
		 		createControlElement();		
				_startDetector();
 			},
			/**
			 * Adds listeners to the ontextsizechange event. 
			 * Returns the base font size
			 * 
			 */
 			addEventListener:function(fn,obj,bScope) {
				aListeners[aListeners.length] = {
					fn: fn,
					obj: obj
				}
				return iBase;
			},
			/**
			 * performs the detection and fires textSizeChanged event
			 * @return the current font size
			 * @type {integer}
			 */
 			detect:function() {
 				return _detect();
 			},
 			/**
 			 * Returns the height of the control element
 			 * 
			 * @return the current height of control element
			 * @type {integer}
 			 */
 			getSize:function() {
	 				var iSize;
			 		return el.offsetHeight;
		 		
		 		
 			},
 			/**
 			 * Stops the detector
 			 */
 			stopDetector:function() {
				return _stopDetector();
			},
			/*
			 * Starts the detector
			 */
 			startDetector:function() {
				return _startDetector();
			}
 	}
 }();

TextResizeDetector.TARGET_ELEMENT_ID = 'doc';
TextResizeDetector.USER_INIT_FUNC = null;




   function init()  {
     var iBase = TextResizeDetector.addEventListener(onFontResize,null);  
  }
  function onFontResize(e,args) {

   sizes();

  }
   function sortNumber(a,b)
   {
   return a - b;
   }  
  //id of element to check for and insert control
  TextResizeDetector.TARGET_ELEMENT_ID = 'container';
  //function to call once TextResizeDetector has init'd
  TextResizeDetector.USER_INIT_FUNC = init;
 jQuery(document).ready(function($) {
  setTimeout(function() { sizes() }, 500);
    }); 

    
  function sizes() {
   var div = new Array(3);
   
   var pixString = "0px";
   try {
		pixString = jQuery("#page_col_center .page_rounder_2").css("height");
   } catch(e) {
	   //nothing
	}
   var pr_up= convertCSSpixelsToNum(pixString);
   if (!(pr_up>0)) {
		pr_up = 0;
	}
   pixString = "0px";
   try {
	   pixString = jQuery("#page_col_center .page_rounder_4").css("height");
   } catch(e) {
	   //nothing
   }
   var pr_down= convertCSSpixelsToNum(pixString);
   if (!(pr_down>0)){
		pr_down=0;
	}
	var	rounders=pr_up+pr_down; 
   
   jQuery("#page_col_left").css("height", "auto");
   div[0] = jQuery("#page_col_left").height();
   
   jQuery("#page_content_wrapper").css("height", "auto");
   div[1] = jQuery("#page_content_wrapper").height() + rounders;
   
   jQuery("#page_col_right").css("height", "auto");
   div[2] = jQuery("#page_col_right").height();
 
   
   
   var tval1 = div[0];
   var tval2 = div[1];
   var tval3 = div[2];
   
   if( div[0] == null) {
   div[0]=0;
   }          
   
   if( div[1] == null) {
   div[1]=0;
   }        
 
   if( div[2] == null) {
   div[2]=0;
   }
 
   div.sort(sortNumber);
   var largest = div[2];

   /* 
   if( tval1 != 0) {
    jQuery("#page_col_left").css("height", (largest)+ "px");
   }
   if( tval2 != 0) {
    jQuery("#page_content_wrapper").css("height", (largest)+ "px");
   }
   else {
    jQuery("#page_col_center").css("height", (largest)+ "px");
   
   };
   if( tval3 != 0) {        
    jQuery("#page_col_right").css("height", (largest)+ "px");
   };
   */
   
   if( largest != 0) {   
	if(largest < 400) {  
		largest = 400;
	}	    
	jQuery("#page_col_left").css("height", (largest)+ "px");  
	jQuery("#page_content_wrapper").css("height", (largest - rounders)+ "px");  
	// jQuery("#page_content_wrapper").css("height", (largest)+ "px");  
	jQuery("#page_col_center").css("height", (largest)+ "px");
	jQuery("#page_col_right").css("height", (largest)+ "px");
	
	
	var pixelValue = "0px";
	
	/* sivun alkuun/tulosta sivu linkkien paikka paddingin verran alempana. */
    var emValue = jQuery("#page_col_center").css("padding-bottom");
    if (emValue == null) {
		emValue = "0em";
	}   
	// alert("emValue" + emValue + " pixelValue " + (pixelValue) + " rounders " + rounders);
	if (emValue.indexOf("em") < 0){
		if (emValue.indexOf("px") > -1){
			pixelValue = convertCSSpixelsToNum(emValue);
			// alert("emValuePX" + emValue + " pixelValue " + (pixelValue) + " rounders " + rounders);
		}
	} else {
		pixelValue = convertCSSpixelsToNum(emValue.pxToEm()); 
	}	
	// alert("emValue" + emValue + " pixelValue " + (pixelValue) + " rounders " + rounders);
	
	// var scopeElement = jQuery("#page_content_wrapper"); //element being used for scope. It has a font size of 14px.
	// var pixelValue = emValue.pxToEm({'scope': scopeElement}); 
			
	// alert("largest " + largest + " pixelValue " + (pixelValue) + " rounders " + rounders);
    jQuery("#page .inner_page").css("height", (largest + pixelValue)+ "px");
    jQuery("#page .inner_page").css("width", "100%");
    jQuery("#page .inner_page").css("overflow", "hidden");
    jQuery("#page .form_wrapper").css("height", "auto");
   };
  }; 

  
  function convertCSSpixelsToNum(tString) {
	  var strippedString = "" + tString;
	  var strippedString = strippedString.replace('px', '');
	  var num = parseInt(strippedString);
	  if (!(num>0)){
		num=0;
	  }
	  return num;
  }
  
//fixing js errors
function resizeNavColumn(){
}

function mozResize(){
}

function mozImageCheck(){
}


function doResizeStuff() {
    sizes();
};

var resizeTimer = null;
$(window).bind('resize', function() {
    if (resizeTimer) clearTimeout(resizeTimer);
    resizeTimer = setTimeout(doResizeStuff, 500);

}); 




/*-------------------------------------------------------------------- 
 * javascript method: "pxToEm"
 * by:
   Scott Jehl (scott@filamentgroup.com) 
   Maggie Wachs (maggie@filamentgroup.com)
   http://www.filamentgroup.com
 *
 * Copyright (c) 2008 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
 * Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
 * Demo: http://www.filamentgroup.com/examples/pxToEm/	 	
 *							
 * Options:  	 								
 		scope: string or jQuery selector for font-size scoping
 		reverse: Boolean, true reverses the conversion to em-px
 * Dependencies: jQuery library						  
 * Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
 *
 * Version: 2.0, 08.01.2008 
 * Changelog:
 *		08.02.2007 initial Version 1.0
 *		08.01.2008 - fixed font-size calculation for IE
 MODIFIED BY P.Piirto
 
--------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({
		scope: 'body',
		reverse: true
	}, settings);
	
	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};	
	
	/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
		For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
		When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
		to get an accurate em value. */
				
	if (settings.scope == 'body' && jQuery.browser.msie && (parseFloat(jQuery('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){		
			return (parseFloat(jQuery('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };
			
	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) : (pxVal / scopeVal).toFixed(2);
	return parseInt(result);
};


/*-------------------------------------------------------------------- 
 * Toiminnallisuus textarean maksimimerkkim??r?n rajaamiseksi
 */


//Find language for translation
var url=document.location.href;
var langArr;
if (url.indexOf("/sv/")>0){
	langArr = ["Du kan skriva ", " tecken i textfält. Du har ",  " tecken kvar."];
}else if (url.indexOf("/en/")>0){
	langArr = ["You can write ", " characters into the textfield. You have ",  " characters left."];
}else{
	langArr = ["Voit syöttää tekstialueeseen ", " merkkiä, joista jäljellä ",""];
}
//Lisätään lomakkeen maksimimäärät  

jQuery(document).ready(function() {
	$("div.form_element_input textarea").each(function() {			
		var textAreaText = "";		
	    var max= $(this).attr("maxlength"); 
		max = parseInt(max);    
		if (max > 0){
			$(this).parent().append("<div class=\"charLeft\">&nbsp;</div><br/>");
			var charLeftElement = $(this).parent().find(".charLeft");
			//charLeftElement.html("" + langArr[0]+max+langArr[1]+max+langArr[2]);
			$(this).keyup(function() {
	                textAreaText = $(this).val();
	                var len = textAreaText.length;                
	                len=max-len;
	                if (len < 0) {
	                	var shortenedText = textAreaText.substring(0,max);
	                	$(this).val(shortenedText);
	                	len = 0;
                	}
					charLeftElement.html("" + langArr[0]+max+langArr[1]+len+langArr[2]);	                
					//this.scrollTop = this.scrollHeight - this.clientHeight;
					//alert("1:"+this.scrollTop+" 2:"+this.scrollHeight+" 3:"+this.clientHeight);

	            });
	       	$(this).keyup();
	       	
			}
	});
});





