var isTabletApp = false;

var params = {"domain" : "messages_js","locale_data" : json_locale_data};
var gt = new Gettext(params);
function _ (msgid) { return gt.gettext(msgid); }

// jquery functions overwriting

if(isTabletApp)
{
	(function()
	{
		jQuery.fn.fadeIn = function(speed, callback)
		{
			jQuery.fn.css.apply( this, [{display: "block"}] )
			if(typeof(callback) == 'function')
				callback.apply(this);
		}
		
		jQuery.fn.fadeOut = function(speed, callback)
		{
			jQuery.fn.css.apply( this, [{display: "none"}] )
			if(typeof(callback) == 'function')
				callback.apply(this);
		}
		
	})();
}

jQuery.fn.extend({ 
    disableSelection : function() { 
            this.each(function() { 
                    this.onselectstart = function() { return false; }; 
                    this.unselectable = "on"; 
                    jQuery(this).css('-moz-user-select', 'none'); 
            }); 
    } 
});

$(document).bind('ready', globalOnReady);

function globalOnReady()
{
	$('img, a, div').disableSelection();
	$('img, a').live('dragstart', function(event){event.preventDefault();});	
}

//Post page functions

function postReady()
{
	$('#post-up-button div.deactivate-button').show();
	
	if($('#post-body').outerHeight(true) > $('#post-body-container').height())
	{
		$('#gradient-bottom').css('top', ($('#post-body-container').height() - $('#gradient-bottom').height())+ 'px');
		$('#gradient-bottom').show();
	}
	else
	{
		$('#post-down-button div.deactivate-button').show();
	}
}

var postScroll = 50;

function postBodyDown()
{
	if($('#post-body').position().top <= ($('#post-body-container').height() - $('#post-body').outerHeight(true)))
			return;
	
	var offset = ($('#post-body').position().top - postScroll) < ($('#post-body-container').height() - $('#post-body').outerHeight(true)) ? Math.abs(($('#post-body-container').height() - $('#post-body').outerHeight(true)) - $('#post-body').position().top) : postScroll;
	var topValue = $('#post-body').position().top - offset;
	
	$('#gradient-top').show();
	$('#post-up-button div.deactivate-button').hide();
	
	$("#post-body").animate({top: topValue}, {duration: 'fast', complete:function(){
	
		if(topValue <= ($('#post-body-container').height() - $('#post-body').outerHeight(true)))
		{
			$('#post-down-button div.deactivate-button').show();
			$('#gradient-bottom').hide();
		}
	
	}});
}

function postBodyUp()
{
	if($('#post-body').position().top == 0)
		return;

	var offset = ($('#post-body').position().top + postScroll) > 0 ? Math.abs($('#post-body').position().top) : postScroll;
	var topValue = (($('#post-body').position().top + offset) > 0) ? 0 : ($('#post-body').position().top + offset);
	
	$('#gradient-bottom').show();
	$('#post-down-button div.deactivate-button').hide();
	
	$("#post-body").animate({top: topValue}, {duration: 'fast', complete:function(){
		
		if(topValue == 0)
		{
			$('#post-up-button div.deactivate-button').show();
			$('#gradient-top').hide();
		}
		
	}});
}

//List of post functions

function listReady()
{
	activatePost(0);
	
	$('#list-up-button div.deactivate-button').show();
	
//	if($('#list-body').outerHeight(true) > $('#post-list-container').height())
//	{
//		$('#gradient-bottom').css('top', ($('#post-list-container').height() - $('#gradient-bottom').height())+ 'px');
//		$('#gradient-bottom').show();
//	}	
}

var activePost;

function activatePost(post)
{
	var listItemCount = $('#list-body .post-list-item').length;
	
	if(post == activePost)
		return;
	
	$('#post-list-item-' + activePost).removeClass('active');
	$('#post-list-item-' + activePost+' span.news-date, #post-list-item-' + activePost+' h2.news-title a, #post-list-item-' + activePost + ' p').removeClass('active');
	
	$('#post-list-item-' + post).addClass('active');
	$('#post-list-item-' + post + ' span.news-date, #post-list-item-' + post + ' h2.news-title a, #post-list-item-' + post + ' p').addClass('active');
	
	
/*	$('#post-list-item-'+activePost).css({ background: "transparent url('images/black-transparency-0.4.png') repeat left top"});
	$('#post-list-item-'+activePost+' span.news-date, #post-list-item-'+activePost+' h2.news-title a, #post-list-item-'+activePost+' p').css({color: "white"});
	
	$('#post-list-item-'+post).css({ background: "transparent url('images/white-transparency-0.4.png') repeat left top"});
	$('#post-list-item-'+post+' span.news-date, #post-list-item-'+post+' h2.news-title a, #post-list-item-'+post+' p').css({color: "black"});*/	
	
	if(post > activePost) // Down
	{
		if((($('#post-list-item-' + post).position().top - Math.abs($('#list-body').position().top)) + $('#post-list-item-' + post).outerHeight()) > $('#post-list-container').height())
		{
			//$('#gradient-top').show();
			var topValue = ($('#list-body').position().top - ((($('#post-list-item-' + post).position().top - Math.abs($('#list-body').position().top)) + $('#post-list-item-' + post).outerHeight(true)) - $('#post-list-container').height()));
			$("#list-body").animate({top: topValue}, 'fast');

		}
		
		$('#list-up-button div.deactivate-button').hide();
		
		if(post + 1 >= listItemCount)
		{
			$('#list-down-button div.deactivate-button').show();
			//$('#gradient-bottom').hide();
		}		
	}
	else if(post < activePost) // Up
	{
		if(($('#post-list-item-' + post).position().top ) < Math.abs($('#list-body').position().top))
		{
			//$('#gradient-bottom').show();
			var topValue = ($('#list-body').position().top + ((Math.abs($('#list-body').position().top)) - $('#post-list-item-' + post).position().top));
			$("#list-body").animate({top: topValue}, 'fast');
			
		}
		
		$('#list-down-button div.deactivate-button').hide();
		
		if(post <= 0)
		{
			$('#list-up-button div.deactivate-button').show();
			//$('#gradient-top').hide();
		}		
	}	
	
	activePost = post;
}

function postListDown()
{
	var listItemCount = $('#list-body .post-list-item').length;
	if(activePost + 1 >= listItemCount)
			return;
	
	activatePost(activePost + 1); 
}

function postListUp()
{
	if(activePost <= 0)
		return;
	
	activatePost(activePost - 1);
}

function showPost()
{
	var postUrl = $('#post-list-item-' + activePost + ' h2.news-title a').attr('href');
	location.href = postUrl;
}

//Gallery Functions
var gallery;
var supportOgg;

function mediaReady(items, source)
{
	var referrer = 'http://siestamenu/app/internet/internet.php';
	gallery = new IFreeGallery('ifreeflow', items, actionCallback);
	
	for(var i = 0; i < items.length ; i++)
	{
		if(items[i].type == 'imagen')
			items[i].viewer = $('<a style="display: none;" rel="cbitems" id="cboxlink'+i+'"></a>').appendTo('body').colorbox({href:items[i].source, title: items[i].description, open: false, rel: "cbitems", maxWidth: '95%', maxHeight: '95%'});
	}
	
	if(source == 'remote')
	{
		if(document.referrer.substring(0, referrer.length) == referrer)
		{
			$('.global-back-container').attr('href', '/');
		}
	}
	else
	{
		if(document.referrer == '' || document.referrer == undefined)
		{
			$('.global-back-container').attr('href', '/');
		}		
	}
	
	$('#search_box').focus(searchBoxOnFocus);
	$('#search_box').blur(searchBoxOnBlur);
	$('#search_box').keypress(searchBoxOnEnter);
	$('#search_box').val('');
	searchBoxOnBlur();
	
	$(window).blur(function(event){$('#search_box').blur();});
	$('#select-button').mousedown(function(event){ if($('#search_box').hasClass('focus')) event.preventDefault();});
	$('#video-viewer .mediadisplay').bind('dblclick', onVideoDblClick);
	
	$('#select-button').bind('click', selectButtonOnClick);
	
	supportOgg = browserSupportOgg();
}

function actionCallback(item)
{
	if(item.type == 'imagen')
	{
		item.viewer.colorbox.launch(item.viewer);
	}
	else if(item.type == 'category' || item.type == 'link')
	{
		window.open(item.source);
	}
	else if(item.type == 'video')
	{
		openVideo(item.source, '');	
	}
	else if(item.type == 'audio')
	{
		openAudio(item.source, '');	
	}	
}

function galleryBack()
{
	//jQuery.get('/app/voz/voz.php?voz=\"anterior\"');
	gallery.moveToPrevious();
}

function galleryForward()
{
	//jQuery.get('/app/voz/voz.php?voz="siguiente"');
	gallery.moveToNext();
}

function selectActiveItem()
{
	//jQuery.get('/app/voz/voz.php?voz="seleccionar"');
	gallery.selectActiveItem();
}

function gallerySearch()
{
	gallery.search($('#search_box').val());
	$('#search_box').val('');
	
	if($('#search_box').hasClass('focus'))
		$('#search_box').blur();
}

function galleryClose(menu)
{
	//jQuery.get('/app/voz/voz.php?voz=\"atrás\"'); 
	if(menu != '' && menu != undefined)
		location.href = '/?menu=' + menu;
	else
		location.href = '/';
		//history.go(-1);
}

function searchBoxFocus()
{
	$('#search_box').focus();
}

function searchBoxOnFocus(event)
{
	if($('#search_box').attr('alt') == 'buscar')
	{
		//jQuery.get('applauncher.php?type=keyboard');
		//jQuery.get('/app/voz/voz.php?voz="buscar"');
		$('#search_box').css({color: 'black'});
		$('#search_box').val('');
		$('#search_box').attr('alt', '');
	}
	
	$('#search_box').addClass('focus');
	$('#select-button .caption').text('6. ' + _('Buscar'));
}

function searchBoxOnBlur(event)
{
	if($('#search_box').val() == '')
	{
		$('#search_box').css({color: 'grey'});
		$('#search_box').val(_('buscar') +' ...');
		$('#select-button .caption').text('6. ' + _('Seleccionar'));
		$('#search_box').attr('alt', 'buscar');
	}
	
	$('#search_box').removeClass('focus');
}

function selectButtonOnClick()
{
	if($('#search_box').attr('alt') == 'buscar')
		selectActiveItem();
	else
		gallerySearch();
	
	$('#select-button').unbind('click', selectButtonOnClick);
	setTimeout("$('#select-button').bind('click', selectButtonOnClick)", 3000);
}

function searchBoxOnEnter(event)
{
	if (event.keyCode == '13')
	{
		gallerySearch();
	}
}

// Photo viewer Functions

function viewerNext()
{
	//jQuery.get('/app/voz/voz.php?voz="siguiente"');
	$.fn.colorbox.next();
}

function viewerBack()
{
	//jQuery.get('/app/voz/voz.php?voz="anterior"');
	$.fn.colorbox.prev();
}

function viewerClose()
{
	//jQuery.get('/app/voz/voz.php?voz="cerrar"');
	$.fn.colorbox.close();
}

// Video viewer functions

var videoState = null;
var mpinstance = null;

function openVideo(source, poster)
{
	$.openDOMWindow({windowSourceID: '#video-wrapper', overlay: 1, overlayColor: 'black', borderSize: 0, height: 568, width: 854, windowPadding: 0, windowSource: 'inline', windowBGColor: 'transparent', overlayOpacity: '50', fixedWindowY:9 }); 
	$('#DOMWindow').bind('unload', onCloseMedia);
	
	if(!supportOgg)
	{
		source = source.substr(0, source.lastIndexOf('.')) || source;
		source = source + '.mp4';
	}
	
	mpinstance =  $('#video-viewer .mediaplayerdialog').mediaplayer({ file: source, image: poster });
	mpinstance.onMediaUpdate = onMediaUpdate;
}

function browserSupportOgg()
{
	var v = document.createElement('video');
	return !!(v.canPlayType && v.canPlayType('video/ogg; codecs="theora, vorbis"').replace(/no/, ''));
}

function closeVideo()
{
	$.closeDOMWindow({windowSourceID: '#video-viewer'});
}

function fullScreenVideo()
{
	mpinstance.node.player.fullScreen(true);
	$(document).bind('keydown', onVideoEsc);
	mpinstance.fullScreen = true;
	$('#video-bar').css('z-index', 100);
}

function outFullScreen()
{
	mpinstance.node.player.fullScreen(false);
	$(document).unbind('keydown', onVideoEsc);
	mpinstance.fullScreen = false;
	$('#video-bar').css('z-index', 300);
}

function onVideoEsc(event)
{
	if((event.type == 'keydown' && event.keyCode == 27))
	{
		outFullScreen();
	}
}

function onVideoDblClick(event)
{
	if(mpinstance.fullScreen)
		outFullScreen();
	else
		fullScreenVideo();
}

function fastForwardVideo()
{

}

function fastBackVideo()
{
	
}

// Common media functions

/* playerready, buffering, stopped, paused, playing, progress, update, meta, complete */
function onMediaUpdate(data)
{
	if(data.type == 'playing')
	{
		videoState = data.type;
		$('.play-pause .caption').text('6. ' + _('Pausa'));
	}
	else if(data.type == 'stopped' || data.type == 'paused')
	{
		videoState = data.type;
		$('.play-pause .caption').text('6. ' + _('Play'));
	}	
	else if(data.type == 'complete')
	{
		if(videoState != 'complete')
		{
			mpinstance.node.player.media.player.stopMedia();
			$('.play-pause .caption').text('6. ' + _('Play'));
			videoState = data.type;
			
			if(mpinstance.fullScreen == true)
				outFullScreen();
			
			mpinstance.node.player.showPreview(true);
			
		}
	}
}

function onCloseMedia()
{
	if(mpinstance.node.player.media.mediaFile.player == 'html5')
	{
		mpinstance.node.player.media.player.player.src = '';
		mpinstance.node.player.media.player.player.load();		
	}
	
	mpinstance.node.player.media.player.stopMedia();
}

function playPauseMedia()
{
	if(videoState == 'stopped' || videoState == 'paused')
	{
		mpinstance.node.player.media.player.playMedia();
	}
	else if(videoState == 'playing')
	{
		mpinstance.node.player.media.player.pauseMedia();
	}
}

// Audio player Functions

function openAudio(source, poster)
{
	$.openDOMWindow({windowSourceID: '#audio-wrapper', overlay: 1, overlayColor: 'black', borderSize: 0, height: 460, width: 500, windowPadding: 0, windowSource: 'inline', windowBGColor: 'transparent', overlayOpacity: '50', fixedWindowY:9 }); 
	$('#DOMWindow').bind('unload', onCloseMedia);
	
	if(!supportOgg)
	{
		source = source.substr(0, source.lastIndexOf('.')) || source;
		source = source + '.mp4';
	}	
	
	poster = poster ? poster : 'images/fondo_audio.jpg';
	
	mpinstance =  $('#audio-player .mediaplayerdialog').mediaplayer({ file: source, image: poster });
	mpinstance.onMediaUpdate = onMediaUpdate;
}

function closeAudio()
{
	$.closeDOMWindow({windowSourceID: '#audio-wrapper'});
}

function fastForwardAudio()
{

}

function fastBackAudio()
{
	
}

function downloadImage()
{
	path = $('#cboxPhoto').attr('src');
	location.href = 'download.php?path=' + path;
}

function downloadAudioVideo()
{
	path = gallery._items[gallery._activeItemIndex].source;
	location.href = 'download.php?path=' + path;
}

var homeVideoSource = '';
var homeVideoPoster = '';

function downloadHomeVideo()
{
	location.href = 'download.php?path=' + homeVideoSource;
}

// Error page Functions

function errorReady(source)
{
	var referrer = 'http://siestamenu/app/internet/internet.php';
	
	if(source == 'remote')
	{
		if(document.referrer.substring(0, referrer.length) == referrer)
		{
			$('.global-back-container').attr('href', '/');
		}
	}
	else
	{
		if(document.referrer == '' || document.referrer == undefined)	
		{
			$('.global-back-container').attr('href', '/');
		}		
	}
}

function closeError()
{
	$.closeDOMWindow({windowSourceID: '#error-box'});
}

function onOpenError()
{
	$('#DOMWindow').css({'-moz-box-shadow':'none','box-shadow':'none','-webkit-box-shadow':'none'});
}

//Menu functions

function indexReady(message, menu)
{
	var sc = $(".top-row").scrollable({ next: '.top-row-next', prev: '.top-row-prev'}).data('scrollable'); 
	if(sc.getSize() <= 1) { $('.top-row-next').addClass('disabled'); $('.top-row-prev').addClass('disabled');} // Fixed jQuery tools bug on one item scrollable
	
	if(message != '')
	{
		$('#contact-advice .advice-message-text').text(message);
		
		$("#contact-advice").show('slide',{direction: "up"},100, function(){
			$("#contact-advice .advice-message-text").effect("highlight", {}, 500, function(){
				setTimeout('$("#contact-advice").hide("slide",{direction: "up"},100);', 3000);
			});
		});
	}
	
	if(menu != '' && menu != undefined)
		showMenu(menu, true);
	else
		initializeHomeVideo();
}

var videoInitialized = false;
function initializeHomeVideo()
{
	supportOgg = browserSupportOgg();
	homeVideoSource = '/media/videos-presentacion/imfree.ogg';
	homeVideoPoster = '/media/fotos-presentacion/tablet.jpg';
	
	if(!supportOgg)
	{
		homeVideoSource = homeVideoSource.substr(0, homeVideoSource.lastIndexOf('.')) || homeVideoSource;
		homeVideoSource = homeVideoSource + '.mp4';
	}
	
	mpinstance =  $('#video-viewer .mediaplayerdialog').mediaplayer({ file: homeVideoSource, image: homeVideoPoster });
	mpinstance.onMediaUpdate = onMediaUpdate;
	
	$('#video-viewer').mouseenter(function(){$('#video-bar').show();}).mouseleave(function(){$('#video-bar').hide();});
	$('#video-viewer .mediadisplay').bind('dblclick', onVideoDblClick);	
	
	videoInitialized = true;
	
	homeVideoSource = '/media/videos-presentacion/imfree.ogg';
}

function showMenu(menu, init)
{
	if(videoState == 'playing')
		mpinstance.node.player.media.player.pauseMedia();
	
	if($("#" + menu + ' .mid-row').data('scrollable') == undefined)
	{
		var sc = $("#" + menu + ' .mid-row').scrollable({ next: '.mid-row-next', prev: '.mid-row-prev', onSeek: onSeekMenu}).data('scrollable');
		if(sc.getSize() <= 1) { $("#" + menu + ' .mid-row-next').addClass('disabled'); $("#" + menu + ' .mid-row-prev').addClass('disabled');} // Fixed jQuery tools bug on one item scrollable
	}
	
	$("#home-image").fadeOut(250, function()
	{
		$("#" + menu).css({opacity: 1});
		$("#" + menu).fadeIn(250);
	});
	
	var loadSpeed = init ? 0 : 250;
	
	$("#" + menu).expose({ color: '#000', loadSpeed: loadSpeed, closeSpeed: 250, closeOnClick: false, closeOnEsc: false});
}

function hideMenu(menu)
{
	$("#" + menu).animate({opacity: 0.01}, {duration: 250, complete: function()
	{
		$("#" + menu).css({display: 'none'});
		$.mask.close();
		$("#home-image").fadeIn(250);
		
		if(!videoInitialized)
			initializeHomeVideo();
	}});
	
}

function onSeekMenu(event, index)
{
	
	if(this.getIndex() == 0)
	{
		$($(this.getItemWrap().parents('.menu-container')[0]).children('.back-menu-button')[0]).css({display: 'block'});
		$($(this.getItemWrap().parents('.menu-container')[0]).children('.minus-button')[0]).css({display: 'none'});
	}
	else
	{
		$($(this.getItemWrap().parents('.menu-container')[0]).children('.back-menu-button')[0]).css({display: 'none'});
		$($(this.getItemWrap().parents('.menu-container')[0]).children('.minus-button')[0]).css({display: 'block'});	
	}
}

/* Comments functions */

function openComments()
{
	$.openDOMWindow({
		windowSourceID: '#comments-container', 
		overlay: 1, overlayColor: 'black', 
		borderSize: 0, 
		height: 489, 
		width: 869, 
		windowPadding: 0, 
		windowSource: 'inline', 
		windowBGColor: 'transparent', 
		overlayOpacity: '50', 
		fixedWindowY:9,
		functionCallOnOpen: onOpenComments,
		functionCallOnClose: onCloseComments
	}); 
}

function onOpenComments()
{
	var comments_bottom = $('#commentlist').position().top + $('#commentlist').outerHeight();
	var box_bottom =  $('#comments-wrapper').height();
	var comments_top = $('#commentlist').position().top;
	var box_top =  10;
	
	if(comments_bottom <= box_bottom)
		$('#comments-down-button div.deactivate-button').show();
	
	if(comments_top >= box_top)
		$('#comments-up-button div.deactivate-button').show();
}

function commentsClose()
{
	$.closeDOMWindow();
	$('#comment-text').val('');
}

function onCloseComments()
{
	$('#comment-text').val('');
}

function commentsUp()
{
	var comments_top = $('#commentlist').position().top;
	var box_top =  10;
	var stepSize = 50;
	
	if(comments_top <= box_top)
	{
		var offset = ((box_top - comments_top) <= stepSize) ? (box_top - comments_top) : stepSize;
		var topValue = $('#commentlist').position().top + offset;
		
		$("#commentlist").animate({top: topValue}, {duration: 'fast', complete:function()
		{
			$('#comments-down-button div.deactivate-button').hide();
		}});
		
		if((box_top - comments_top) <= stepSize)
		{
			$('#comments-up-button div.deactivate-button').show();
		}		
	}	
}

function commentsDown()
{
	var comments_bottom = $('#commentlist').position().top + $('#commentlist').outerHeight();
	var box_bottom =  $('#comments-wrapper').height();
	var stepSize = 50;
	
	if(comments_bottom >= box_bottom)
	{
		var offset = ((comments_bottom - box_bottom) <= stepSize) ? (comments_bottom - box_bottom) : stepSize;
		var topValue = $('#commentlist').position().top - offset;
		
		$("#commentlist").animate({top: topValue}, {duration: 'fast', complete:function()
		{
			$('#comments-up-button div.deactivate-button').hide();
		}});
		
		if((comments_bottom - box_bottom) <= stepSize)
		{
			$('#comments-down-button div.deactivate-button').show();
		}
	}
}

function commentSend()
{
	var invalid = { global : false, text_empty : false, email_empty : false, email_invalid: false };
	
	if($('#comment-text').val() == '')
	{
		invalid.global = true;
		invalid.text_empty = true;
	}
	
	if($('#comment-email').val() == '')
	{
		invalid.global = true;
		invalid.email_empty = true;
	}
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test($('#comment-email').val()) == false) 
	{
		invalid.global = true;
		invalid.email_invalid = true;
	}
	
	if(invalid.global)
	{
		$('#advice-message .advice-message-text').text(_('Debes insertar un comentario y una dirección de correo electrónico válida.'));
		
		$("#advice-message").show('slide',{direction: "up"},100, function(){
			$("#advice-message .advice-message-text").effect("highlight", {}, 500, function(){
				setTimeout('$("#advice-message").hide("slide",{direction: "up"},100);', 3000);
			});
		});
		
		if(invalid.text_empty)
			$('#comment-text').effect("highlight", {}, 1000);
		
		if(invalid.email_empty || invalid.email_invalid)
			$('#comment-email').effect("highlight", {}, 1000);
	}
	else
	{	
		$.post($('#commentform').attr('action'), { author: 'anonymous', email: $('#comment-email').val(), url: '', comment: $('#comment-text').val(), comment_post_ID: $('#comment_post_ID').val(), comment_parent: $('#comment_parent').val() }, commentSent);
	}
}

function commentSent(data, textStatus, XMLHttpRequest)
{
	$('#comment-text').val('');
	
	$('#advice-message .advice-message-text').text(_('Se ha insertado tu comentario, muy pronto se publicará.'));
	
	$("#advice-message").show('slide',{direction: "up"},100, function(){
		$("#advice-message .advice-message-text").effect("highlight", {}, 500, function(){
			setTimeout('$("#advice-message").hide("slide",{direction: "up"},100);', 3000);
		});
	});
}

/* Contact functions */

function contactReady()
{
	$('#contact-name').val('');
	$('#contact-email').val('');
	$('#contact-phone').val('');
	$('#contact-comment').val('');
	$('#contact-surname').val('');
	$('#contact-address').val('');
	$('#contact-country').val('');
	$('#contact-city').val('');
	
	$('#contact-container .field').bind('focus', onContactFieldFocus);
	$('#contact-container .field').bind('blur', onContactFieldBlur);
	
	$('#contact-up-button').click(contactUp);
	$('#contact-down-button').click(contactDown);
	
	$('#contact-name').focus();
}

fieldIndex = 0;

function onContactFieldFocus(event)
{
	if(!$(this).parent().hasClass('focus'))
	{
		$(this).parent().addClass('focus');
		fieldIndex = $(this).attr('tabindex');
	}
}

function onContactFieldBlur(event)
{
	if($(this).parent().hasClass('focus'))
	{
		$(this).parent().removeClass('focus');
		fieldIndex = $(this).attr('tabindex');
	}
}

function contactUp(event)
{
	tabindex = parseInt(fieldIndex) - 1;
	
	if(tabindex >= 1)
		$('#contact-container .field' + tabindex).focus();
	else
		$('#contact-container .field1').focus();
}

function contactDown(event)
{
	tabindex = parseInt(fieldIndex) + 1;
	
	if(tabindex <= 8)
		$('#contact-container .field' + tabindex).focus();
	else
		$('#contact-container .field8').focus();	
}

function contactSend()
{
	$('#contact-container .contact-name-container label').css({color: 'black', fontWeight: 'normal'});
	$('#contact-container .contact-comment-container label').css({color: 'black', fontWeight: 'normal'});
	$('#contact-container .contact-email-container label').css({color: 'black', fontWeight: 'normal'});		
	$('#contact-container .contact-phone-container label').css({color: 'black', fontWeight: 'normal'});
	$('#contact-container .contact-country-container label').css({color: 'black', fontWeight: 'normal'});
	$('#contact-container .contact-city-container label').css({color: 'black', fontWeight: 'normal'});
	$('#contact-container .contact-surname-container label').css({color: 'black', fontWeight: 'normal'});
	$('#contact-container .contact-address-container label').css({color: 'black', fontWeight: 'normal'});
	
	var invalid = { global : false, name_empty : false, phone_empty : false, phone_invalid : false, text_empty : false, email_empty : false, email_invalid: false, country_empty : false, city_empty : false, surname_empty : false, address_empty : false };
	
	if($('#contact-comment').val() == '')
	{
		invalid.global = true;
		invalid.text_empty = true;
	}
	
	if($('#contact-email').val() == '')
	{
		invalid.global = true;
		invalid.email_empty = true;
	}
	
	if($('#contact-phone').val() == '')
	{
		invalid.global = true;
		invalid.phone_empty = true;
	}
	
	if($('#contact-surname').val() == '')
	{
		invalid.global = true;
		invalid.surname_empty = true;
	}
	
	if($('#contact-address').val() == '')
	{
		invalid.global = true;
		invalid.address_empty = true;
	}
	
	if($('#contact-country').val() == '')
	{
		invalid.global = true;
		invalid.country_empty = true;
	}
	
	if($('#contact-city').val() == '')
	{
		invalid.global = true;
		invalid.city_empty = true;
	}
	
	if($('#contact-name').val() == '')
	{
		invalid.global = true;
		invalid.name_empty = true;
	}	
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test($('#contact-email').val()) == false) 
	{
		invalid.global = true;
		invalid.email_invalid = true;
	}
	
	var reg = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
	if(reg.test($('#contact-phone').val()) == false && $('#contact-phone').val() != '') 
	{
		invalid.global = true;
		invalid.phone_invalid = true;
	}	
	
	if(invalid.global)
	{
		$('#contact-advice .advice-message-text').text(_('Revisa los campos resaltados, deben contener valores válidos.'));
		
		$("#contact-advice").show('slide',{direction: "up"},100, function(){
			$("#contact-advice .advice-message-text").effect("highlight", {}, 500, function(){
				setTimeout('$("#contact-advice").hide("slide",{direction: "up"},100);', 3000);
			});
		});
		
		if(invalid.name_empty)
			$('#contact-container .contact-name-container label').css({color: 'red', fontWeight: 'bold'});

		if(invalid.country_empty)
			$('#contact-container .contact-country-container label').css({color: 'red', fontWeight: 'bold'});
		
		if(invalid.surname_empty)
			$('#contact-container .contact-surname-container label').css({color: 'red', fontWeight: 'bold'});
		
		if(invalid.address_empty)
			$('#contact-container .contact-address-container label').css({color: 'red', fontWeight: 'bold'});
		
		if(invalid.city_empty)
			$('#contact-container .contact-city-container label').css({color: 'red', fontWeight: 'bold'});
		
		if(invalid.text_empty)
			$('#contact-container .contact-comment-container label').css({color: 'red', fontWeight: 'bold'});
		
		if(invalid.email_empty || invalid.email_invalid)
			$('#contact-container .contact-email-container label').css({color: 'red', fontWeight: 'bold'});
		
		if(invalid.phone_empty || invalid.phone_invalid)
			$('#contact-container .contact-phone-container label').css({color: 'red', fontWeight: 'bold'});		
	}
	else
	{	
		$('#contact-form').submit();
	}
}

function aviso(message)
{
	$('#error-box .titulo').html(_('Aviso'));
	$('#error-box .sub-titulo').html('');
	$.openDOMWindow({windowSourceID: '#error-box', overlay: 1, borderSize: 0, height: 240, width: 488, windowPadding: 0, windowSource: 'inline', functionCallOnOpen: onOpenError}); 
}