var minColHeight = 470;

if( window.attachEvent ) {
	window.attachEvent( 'onload' , adjustColumnsHeight );
} else { 
	window.addEventListener( 'load' , adjustColumnsHeight , false );
}

var timId = null;

if( /Gecko/.test( navigator.userAgent ) ) {
	window.addEventListener( 'scroll' , fixFlashHitAreas , false );	
}
function fixFlashHitAreas() {
	clearTimeout( timId );
	timId = setTimeout( '_fixFlashHitAreas();' , 500 );
}

function _fixFlashHitAreas() {
	var b = document.body;
	if( b.style.marginTop != '0.01em' ) {
		b.style.marginTop = '0.01em';		
	} else {
		b.style.marginTop = '0pt';
	}		
}

function adjustColumnsHeight() {
	
	var content = document.getElementById('content');
	var leftCol = document.getElementById('leftCol');
	
	if( !content || !leftCol ) return;
	
	content.style.height = leftCol.style.height = Math.max( Math.max( content.offsetHeight , leftCol.offsetHeight ) , minColHeight ) + 'px';
	
}

function scrollPageDown() {
	window.scroll( 0 , document.body.scrollHeight );
	adjustColumnsHeight();
}

function updateCheckBox( labelRef ) {
	var input = labelRef.getElementsByTagName('input');
	if( input && input[0] ) {
		input = input[0];
		input.className = 'Styled';
		if( input.checked ) labelRef.className='CheckBox Checked';
		else labelRef.className='CheckBox';				
	};
}


function validateContestForm(f) {

	var cd = new Date();
	/*
		Dziecko
	*/
	
	if( f.ChildName.value.length < 3 ) {
		alert( 'Podaj imię dziecka. Minimum trzy znaki.' );
		f.ChildName.focus();
		markField(f.ChildName,true);
		return false;
	}
	
	var cbd = makeDate(f.BirthDate.value);
	
	if(  cbd == null  ) {
		alert('Podaj poprawną datę urodzenia dziecka w formacie RRRR-MM-DD.');
		f.BirthDate.focus();
		markField(f.BirthDate,true);		
		return false;
	}
	
	/*
	var d18 = new Date(cd.getTime());
	d18.setMonth( d18.getMonth() - 18 );
	
	var d28 = new Date(cd.getTime());
	d28.setMonth( d28.getMonth() - 28 );
	
	if( cbd.getTime() > d18.getTime() || cbd.getTime() < d28.getTime() ) {
		alert('Zgłoszone w akcji dziecko nie może być młodsze niż 18 miesięcy i starsze niż 28 miesięcy.');
		f.bdate.focus();
		return false;		
	}
	*/
	

	
	if( f.ChildPhoto.value.length < 5 ) {
		alert( 'Wybierz zdjęcie dziecka.' );
		f.ChildPhoto.focus();
		markField(f.ChildPhoto,true);
		return false;
	}
	
	if( !f.ChildPhoto.value.match(/\.(jpg|jpeg|gif|png)$/i) ) {
		alert( 'Niepoprawny format pliku - zdjęcie dziecka. Dozwolone formaty plików to: jpg, gif, png.' );
		f.ChildPhoto.focus();
		markField(f.ChildPhoto,true);
		return false;	
	}	
	
	/*
		Rodzic
	*/

	if( f.ParentName.value.length < 3 ) {
		alert( 'Podaj swoje imię. Minimum trzy znaki.' );
		f.ParentName.focus();
		markField(f.ParentName,true);		
		return false;
	}

	if( f.ParentSurname.value.length < 3 ) {
		alert( 'Podaj swoje nazwisko. Minimum trzy znaki.' );
		f.ParentSurname.focus();
		markField(f.ParentSurname,true);			
		return false;
	}

	if( ! /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/.test( f.Email.value) ) {
		alert( 'Podaj poprawny adres email.' );
		f.Email.focus();
		markField(f.Email,true);		
		return false;
	}
	
	if( ! /^\+?[0-9\(\)\- ]{9,}$/.test( f.Phone.value) ) {
		alert( 'Podaj poprawny numer telefonu, minimalnie 9 cyfr.' );
		f.Phone.focus();
		markField(f.Phone,true);		
		return false;
	}	
	
	if( f.Province.selectedIndex <= 0 ) {
		alert( 'Wybierz województwo.' );
		f.Province.focus();
		markField(f.Province,true);
		return false;
	}
	
	if( f.Address.value.length < 3 ) {
		alert( 'Podaj swój adres zamieszkania.' );
		f.Address.focus();
		markField(f.Address,true);			
		return false;
	}	
	
	var bid = makeDate(f.BalanceDate.value);
	
	if(  bid == null  ) {
		alert('Podaj poprawną datę bilansu w formacie RRRR-MM-DD.');
		f.BalanceDate.focus();
		markField(f.BalanceDate,true);
		return false;
	}
	
	if( bid.getTime() > cd.getTime()+24*60*60*1000 ) {
		alert('Data bilansu nie może być nowsza od aktualnej.');
		f.BalanceDate.focus();
		markField(f.BalanceDate,true);
		return false;	
	}
	
	if( bid.getTime() < cbd.getTime()-24*60*60*1000 ) {
		alert('Data bilansu jest starsza od daty urodzin dziecka.');
		f.BalanceDate.focus();
		markField(f.BalanceDate,true);
		return false;	
	}

	if( f.Scan1.value.length < 5 ) {
		alert( 'Wybierz skan książeczki z danymi dziecka.' );
		f.Scan1.focus();
		markField(f.Scan1,true);
		return false;
	}
	if( !f.Scan1.value.match(/\.(jpg|jpeg|gif|png)$/i) ) {
		alert( 'Niepoprawny format pliku - skan książeczki z danymi dziecka. Dozwolone formaty plików to: jpg, gif, png.' );
		f.Scan1.focus();
		markField(f.Scan1,true);
		return false;	
	}	
	if( f.Scan2.value.length < 5 ) {
		alert( 'Wybierz skan książeczki z wynikami badań.' );
		f.Scan2.focus();
		markField(f.Scan2,true);
		return false;
	}
	if( !f.Scan2.value.match(/\.(jpg|jpeg|gif|png)$/i) ) {
		alert( 'Niepoprawny format pliku - skan książeczki z wynikami badań. Dozwolone formaty plików to: jpg, gif, png.' );
		f.Scan2.focus();
		markField(f.Scan2,true);
		return false;	
	}	
	
	if(!f.Approval1.checked ) {
		alert( 'Wymagane jest zapoznanie się i zaakceptowanie regulaminu konkursu.');
		markField(f.Approval1,true);
		return false;
	}
	if(!f.Approval2.checked ) {
		alert( 'Wymagane jest wyrażenie zgody na przetwarzanie danych osobowych przez firmę NUTRICIA.');
		markField(f.Approval2,true);
		return false;
	}

	return true;

}

function makeDate( val ) { // RRRR-MM-DD
	
	var a = val.split('-');
	var y = parseInt(a[0],10);
	var m = parseInt(a[1],10);
	var d = parseInt(a[2],10);
	
	var fd = new Date( y, m-1, d );		
	
	if( fd == 'Invalid Date' || fd.getMonth()!=m-1  ) {
		null;
	} else {
		return fd;
	}
}

function markField( f , isError ) {
	
	if( isError ) {
		if( f.type == 'text' || f.type == 'textarea' ) {
			f.className = f.className +' Error';
			f.onkeydown = f.onchange = function() {
				markField( this , false );
			}
		} else if( f.type == 'checkbox' ) {
			f.parentNode.className = 'CheckBox Error';
		} else if( f.type == 'select-one' ) {
			var s = document.getElementById("select" + f.name);
			if(s) s.className = s.className + ' Error';
			f._onchange = f.onchange;
			f.onchange = function() {
				this._onchange();
				markField( this , false );				
			}
		} else if( f.type == 'file' ) {
			f.relatedElement.className = f.relatedElement.className +' Error';
			f._onchange = f.onchange;
			f.onchange = function() {
				this._onchange();
				markField( this , false );				
			}
		}
	} else {
		if( f.type == 'text'|| f.type == 'textarea' ) {
			f.className = f.className.replace(/ Error$/,'');
			f.onkeydown = null;
			f.onchange = null;
		} else if( f.type == 'select-one' ) {
			var s = document.getElementById("select" + f.name);
			if(s) s.className = s.className.replace(/ Error$/,'');			
			f.onchange = f._onchange;		
		} else if( f.type == 'file' ) {
			f.relatedElement.className = f.relatedElement.className.replace(/ Error$/,'');
			f.onchange = f._onchange;	
		}
	}
}

function validateContactForm() {

	var f = document.getElementById('contactForm');

	if( f.name.value.length < 3 ) {
		alert( 'Nie wpisano imienia i nazwiska. Przynajmniej trzy znaki.' );
		f.name.focus();
		markField(f.name,true);
		return false;
	}	

	if( ! /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/.test( f.email.value) ) {
		alert( 'Podaj poprawny adres email.' );
		f.email.focus();
		markField(f.email,true);
		return false;
	}
	
	if( f.msg.value.length < 3 ) {
		alert( 'Nie wpisano treści wiadomości.' );
		f.msg.focus();
		markField(f.msg,true);
		return false;
	}
	
	if( !f.agree.checked ) {
		alert( 'Nie wyrażono zgody na otrzymywanie korespondencji od firmy NUTRICIA.' );
		markField(f.agree,true);
		return false;		
	}

	return true;

}

function customizeFormControls() {
	if (!(document.createElement && document.getElementsByTagName)) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'FakeFile';
	var input = document.createElement('input');
	input.className = 'Txt';
	fakeFileUpload.appendChild(input);
	var btn = document.createElement('a');
	btn.className = 'FileBtn';
	fakeFileUpload.appendChild(btn);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className.indexOf('FileInputs')==-1) continue;
		x[i].className = 'HiddenFile';
		var clone = fakeFileUpload.cloneNode(true);
		var a = clone.getElementsByTagName('a')[0];
		a.innerHTML = x[i].getAttribute('title');
		x[i].parentNode.appendChild(clone);
		x[i].relatedBtn = a;
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
	
	if( /Microsoft/.test( navigator.appName ) && ( parseInt( navigator.appVersion.split('MSIE ')[1] ) < 7 ) ) return;
	
	var inputs = document.getElementsByTagName("select");
	var span = [];
	for(var a = 0; a < inputs.length; a++) {
		inputs[a].className = inputs[a].className ? inputs[a].className + ' Styled' : inputs[a].className ;
		var option = inputs[a].getElementsByTagName("option");
		var active = option[0].childNodes[0].nodeValue;
		var textnode = document.createTextNode(active);
		for(var b = 0; b < option.length; b++) {
			if(option[b].selected == true) {
				textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
			}
		}
		span[a] = document.createElement("span");
		span[a].className = "Select";
		span[a].id = "select" + inputs[a].name;
		span[a].appendChild(textnode);
		inputs[a].parentNode.insertBefore(span[a], inputs[a]);
		inputs[a].onchange = function() {
			var option = this.getElementsByTagName("option");
			for(d = 0; d < option.length; d++) {
				if(option[d].selected == true) {
					document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
				}
			}
		}
	}	
	
}

/*
	get pageScrolls postion
*/

function getPageScroll ()
{
	var xScroll, yScroll;
	var _body;
	
	if ( /Microsoft/.test ( navigator.appName ) )
	{
		if ( document.compatMode == 'CSS1Compat' )
		{ 
			_body = document.body.parentNode;
		}
		else
		{
			_body = document.body;
		}
	
		yScroll = _body.scrollTop;
		xScroll = _body.scrollLeft;
	}
	else
	{
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	}

	return [ xScroll , yScroll ];
}

/*
	video player handling	
*/

var p = SWFAddress.getPathNames();
var timVPId;
var timS2FId;
var playerIsShowed = false;
var send2friendIsShowed = false;

if( p && p[0] == 'player' ) {
	
	p = parseInt( p[1] );
	if( isNaN( p ) ) p = 1;
	
	if( window.attachEvent ) {
		window.attachEvent( 'onload' , function(){ setTimeout("showVideoPlayer("+p+")",500)} );
	} else { 
		window.addEventListener( 'load' , function(){setTimeout("showVideoPlayer("+p+")",500)} , false );
	}
};

SWFAddress.addEventListener( SWFAddressEvent.CHANGE , handlerSWFAddressChange );

function handlerSWFAddressChange() {
	var p = SWFAddress.getPathNames();
	
	if( p && p[0] == 'player' ) {
		
		p = parseInt( p[1] );
		if( isNaN( p ) ) p = 1;
		showVideoPlayer(p);
		
	}
}

function initVideoPlayer() {

	var playerDiv = document.createElement( 'div' );
	var playerDivId = document.createAttribute( 'id' );
	playerDivId.value = 'videoPlayer';
	playerDiv.attributes.setNamedItem( playerDivId );

	document.body.appendChild( playerDiv );
	
	var flashCon = document.createElement( 'div' );
	var flashConId = document.createAttribute( 'id' );
	flashConId.value = 'videoPlayerFlash';
	flashCon.attributes.setNamedItem( flashConId );
	
	playerDiv.appendChild( flashCon );
	
	var parameters = { allowscriptaccess : 'always' , wmode: 'transparent' , flashvars : 'gemius_codes='+movies_gemius_codes+'&movies=' + movies + '&toLoad=assets/swf/video_player/video_player.swf&skinURL=assets/swf/video_player/SkinBilans.swf&skinBgColor=0x84785F&strongColor=0x84785F&weakColor=0xF7F3E2&activeColor=0xf27e17' };
	var attributes = { id: 'videoPlayerFlash' , name: 'videoPlayerFlash' , data:"assets/swf/video_player/video_player_preloader.swf", width:"100%", height:"100%" };
	
	swfobject.createSWF( attributes , parameters , 'videoPlayerFlash' );

		
}

function initSend2FriendForm ( f )
{
	var send2friendDiv = document.createElement ( 'div' );
	var send2friendDivId = document.createAttribute ( 'id' );
	send2friendDivId.value = 'send2friend';
	send2friendDiv.attributes.setNamedItem ( send2friendDivId );

	document.body.appendChild ( send2friendDiv );
	
	var flashCon = document.createElement ( 'div' );
	var flashConId = document.createAttribute ( 'id' );
	flashConId.value = 'send2friendFlash';
	flashCon.attributes.setNamedItem ( flashConId );
	
	send2friendDiv.appendChild ( flashCon );
	
	var parameters = { allowscriptaccess : 'always' , wmode: 'transparent' , flashvars : 'statsActive=1&sendURL=home/send2friend&mode='+(f?f:'') };
	var attributes = { id: 'send2friendFlash' , name: 'send2friendFlash' , data:"assets/swf/send2friend.swf", width:"100%", height:"100%" };
	
	swfobject.createSWF ( attributes , parameters , 'send2friendFlash' );
}

function showOverlay ()
{
	var overlayDiv = document.getElementById ( 'overlay' );
	
	if ( !overlayDiv )
	{
		overlayDiv = document.createElement ( 'div' );
		var overlayDivId = document.createAttribute ( 'id' );
		overlayDivId.value = 'overlay';
		overlayDiv.attributes.setNamedItem ( overlayDivId );
		document.body.appendChild ( overlayDiv );		
	}
	
	overlayDiv.style.display = 'block';
	fixOverlayPosition ();
	
	if ( window.attachEvent )
	{
		window.attachEvent ( 'onscroll' , fixOverlayPosition );
		window.attachEvent ( 'onresize' , fixOverlayPositionR );
	}
	else
	{
		window.addEventListener ( 'scroll' , fixOverlayPosition , false );
	}
}

function hideOverlay() {
	
	var overlayDiv = document.getElementById('overlay');
	
	if( overlayDiv ) {
		if( window.detachEvent ) {
			window.detachEvent( 'onscroll' , fixOverlayPosition );
			window.detachEvent( 'onresize' , fixOverlayPositionR );
		} else {
			window.removeEventListener( 'scroll' , fixOverlayPosition , false );
		}
		overlayDiv.style.display = 'none';
	}
}

function fixOverlayPositionR() {
	window.scroll( 0 , 0 );
	fixOverlayPosition();	
}

function fixOverlayPosition ()
{	
	var overlay = document.getElementById ( 'overlay' );
	var s = getPageScroll ();
	overlay.style.left = s[ 0 ] + 'px';
	overlay.style.top = s[ 1 ] + 'px';

	if ( /Microsoft/.test ( navigator.appName ) )
	{
		if ( document.compatMode == 'CSS1Compat' )
		{ 
			_body = document.body.parentNode;
		}
		else
		{
			_body = document.body;
		}
		
		overlay.style.width = _body.clientWidth + 'px';
		overlay.style.height = _body.clientHeight + 'px';	
	}
	
	// fixing player position	
	var player = document.getElementById ( 'videoPlayer' );
	
	if ( player && playerIsShowed )
	{
		player.style.marginTop = ( -211 + s[ 1 ] ) + 'px';	
	}
	
	// fixing send2friend position
	var send2friend = document.getElementById ( 'send2friend' );
	
	if( send2friend && send2friendIsShowed )
	{
		send2friend.style.marginTop = ( -183 + s[ 1 ] ) + 'px';	
	}
}
	
function showVideoPlayer( movieNr ) {
	var player = document.getElementById( 'videoPlayer' );

	if( !player ) {
		if( !timVPId ) {
			initVideoPlayer();
			timVPId = setTimeout( 'showVideoPlayer(' + movieNr + ');' , 1000 );
		}
	} else {
		
		if( player && !playerIsShowed ) {
			timVPId = null;
			playerIsShowed = true;			
			showOverlay();
			player.style.display = 'block';
			playMovie( movieNr );
			
		}
	}
}

function playMovie( movieNr ) {
	
	var vp = document.getElementById( 'videoPlayerFlash' );
	if( vp && vp.playMovie && (typeof vp.playMovie == 'function') ) {
		vp.playMovie( movieNr );	
	} else {
		setTimeout( 'playMovie(' + movieNr + ')' , 200 );
	}
	
}

	
function hideVideoPlayer() {

	var player = document.getElementById( 'videoPlayer' );
	
	if( player && playerIsShowed ) {
		hideOverlay();
		swfobject.removeSWF('videoPlayerFlash');
		document.body.removeChild( player );
		playerIsShowed = false;		
		//SWFAddress.setValue('');
	}
		
}

function hideSend2FriendForm() {
	
	var send2friend = document.getElementById( 'send2friend' );
	
	if( send2friend && send2friendIsShowed ) {
		hideOverlay();
		swfobject.removeSWF('send2friendFlash');
		document.body.removeChild( send2friend );
		send2friendIsShowed = false;
	}	
	
}


function showSend2FriendForm ( f )
{
	//showOverlay();
	//alert( location.pathname + location.search + location.hash );
	var send2friend = document.getElementById ( 'send2friend' );

	if ( !send2friend )
	{
		if ( !timS2FId )
		{
			initSend2FriendForm ( f );
			timS2FId = setTimeout ( 'showSend2FriendForm('+f+')' , 1000 );
		}
	}
	else
	{
		if ( send2friend && !send2friendIsShowed )
		{
			timS2FId = null;
			send2friendIsShowed = true;			
			showOverlay ();
			send2friend.style.display = 'block';
			passVariable ( f )
		}
	}
}

function passVariable ( param )
{	
	var sf = document.getElementById ( 'send2friendFlash' );
	
	if ( sf && sf.passVariables && ( typeof sf.passVariables == 'function' ) )
	{
		sf.passVariables ( param , location.href );	
	}
	else
	{
		setTimeout ( 'passVariable(' + param + ')' , 200 );
	}
}

function ieInnerHTML ( obj, convertToLowerCase )
{
	var zz = obj.innerHTML;
	var z = zz.match ( /<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/g );
	
	if ( z )
	{
		for ( var i = 0; i < z.length; i++ )
		{
			var y;
			var zSaved = z[ i ];
			var attrRE = /\=[a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9ęĘóÓąĄśŚłŁżŻźŹćĆńŃ]+[?\s+|?>]/g;
			
			z[ i ] = z[ i ].replace
			(
				/(<?\w+)|(<\/?\w+)\s/,
				function ( a )
				{
					return a.toLowerCase ();
				}
			);
			
			y = z[ i ].match ( attrRE );
			
			if ( y )
			{
				var j = 0;
				var len = y.length;
				
				while ( j < len )
				{
					var replaceRE = /(\=)([a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9ęĘóÓąĄśŚłŁżŻźŹćĆńŃ]+)?([\s+|?>])/g;
					
					var replacer = function ()
					{
						var args = Array.prototype.slice.call ( arguments );
						return '="' + ( convertToLowerCase ? args[ 2 ].toLowerCase () : args[ 2 ] ) + '"' + args[ 3 ];
					};
					
					z[ i ] = z[ i ].replace ( y[ j ], y[ j ].replace ( replaceRE, replacer ) );
					j++;
				}
			}
			
			zz = zz.replace ( zSaved, z[ i ] );
		}
	}
	
	return zz;
}
