// Procedimiento que válida el formulario de contacto
function formValido( form ){
	if( form.name.value.split(' ').join('') == '' ) {
		alert('Debes ingresar tu nombre');
		form.name.focus();
		return false;
	}
	if( ( form.email.value.split(' ').join('') == '' ) && ( form.phone.value.split(' ').join('') == '' ) ) {
		alert('Debes ingresar tu teléfono o correo electrónico');
		form.phone.focus();
		return false;
	}
	if(  form.email.value.split(' ').join('') != '' ){ 
		var er_email = /^(.+\@.+\..+)$/ ;
		if( !er_email.test(form.email.value) ) {
			alert('El campo email no es válido');
			form.email.focus();
			return false;
		}
	}
	if( form.message.value.split(' ').join('') == '' ) {
		alert('Debes ingresar un mensaje');
		form.message.focus();
		return false;
	}
	return true;
}
function getForm( form ) {
	var query = 'name='+form.name.value+
				'&phone='+form.phone.value+
				'&email='+form.email.value+
				'&message='+form.message.value;
	return query;
}

function enviaForm( form ){
	$.ajax({
		async:true,
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url:"<?php bloginfo('template_directory'); ?>/library/contacto/email.php",
		data: getForm( form ),
		beforeSend:function(){
			$('#feedbackForm').fadeOut('fast', function(){
			    $('#answer').html('Enviando...')
			});
		},
		success: function( datos ) {
			$('#answer').delay(1000).html( datos );
		},
		timeout:8000,
		error:function(){
			$('#answer').html(
				'Ocurrió un error durante el envio del '+
				'mensaje, por favor inténtalo nuevamente.'
			);
		}
	});
}


// comportamiento css3, 
var behaviorUrl = 'wp-content/themes/wp_contintaroja/pie/PIE.htc';
var bh_contacto_loaded = false;
var bh_columns_loaded = false;

var left_side = true;

$(document).ready(function() {
    
    $('#slider').cycle({
        pause:           1,
        fx:       'fade',
        timeout:  4500,
		pager:  '#post-tabs',
        pagerAnchorBuilder: function(idx, slide) {
            return '<div id = "tinta-' + idx + '" class="tinta"> <a href = "javascript:void(0);"><img src="wp-content/themes/wp_contintaroja/images/html/' + (idx + 1) + '.jpg" alt = "contintaroja" /> </a></div>';
        },
		before: function(currSlideElement, nextSlideElement, options, forwardFlag){
			var number = $(nextSlideElement).attr('id').split('last-post-')[1] - 1;
			$('#post-tabs .tinta:not(#tinta-'+number+') a img').fadeTo(0, 0.4);
			$('#post-tabs #tinta-'+number+' a img').fadeTo('fast', 1);
			/*
			$('#post-tabs .tinta a:not(.activeSlide) img').fadeTo(0, 0.4);
			$('#post-tabs .tinta a.activeSlide img').fadeTo('fast', 1);
			*/
		}
    });
	
	// Se establece el efecto similar a un 'slider'
	$('#mostrador').click(function(){
		
		if( left_side ) {
			
			var _height = $('#enlaces').innerHeight();
			
			$('#left-side-container').fadeOut('normal');
			$('#enlaces').fadeIn('normal');
			$('#left-side').animate({width:'0px'},'slow');
			$('#right-side').animate({width:'900px', height:_height},'slow', function() {
                
                if( $.browser.msie && !bh_columns_loaded) {
                    
					// se escoge el elemento y se agrega el comportamiento
					$('.one_column').each(function(){
                        $(this)[0].addBehavior( behaviorUrl );
                    });
                    bh_coolumns_loaded = true;
				}
            });
			
			$('#home, #mostrador').animate({height:_height}, 'slow');
			
			$('#secundaria').slideUp('slow');
			
			$('#enlaces').css('visibility','visible');
			
			left_side = false;
		}
		else{
			
			var _height = '360px';
			
			$('#left-side').animate({width:'900px'},'slow');
			$('#right-side').animate({width:'0px'},'slow');
			$('#left-side-container').fadeIn('normal');
			$('#enlaces').fadeOut('normal', function(){
			    $('#enlaces').css('visibility','hidden');
			});
			
			$('#home, #mostrador, #right-side').animate({height:_height}, 'slow');
			$('html, body').animate({scrollTop:0},'slow');
			
		    
			$('#secundaria').slideDown('slow');
			
			left_side = true;
		}
	});
	
	// se remueve el anuncio
	$('#cerrar_anuncio').click(function(){
		$('#anuncio').slideUp('normal', function(){
			$(this).remove();
		});
	});
	
	$('#post-tabs .tinta img:not(:first)').fadeTo('fast', 0.4);
	
	var settings = {
		speed: 0,
        duration: 0,
        min_cols:3,
		margin: 20,
		wrapper: '#enlaces',
		two_cols:'.two_cols',
		three_cols:'.three_cols',
		four_cols:'.four_cols',
        offy: 70,
        offx: 10
    };
    
    $('.one_column').rqsLayout(settings);
	
	var contact_hidden = true;
	$('#anchor_contacto').click(function(){
		if( contact_hidden ) {
			$('#contacto_container').fadeIn('fast', function(){
				// para ie lte 7
				if( $.browser.msie && !bh_contacto_loaded ) { 
					// se escoge el elemento y se agrega el comportamiento
					$('#contacto')[0].addBehavior( behaviorUrl );
					bh_contacto_loaded = true;
				}
			});
		    contact_hidden = false;
		}
		else{
			$('#contacto_container').fadeOut(0);
		    contact_hidden = true;
		}
	});
	$('#cerrar_contacto').click(function(){
	    $('#contacto_container').fadeOut(0);
		contact_hidden = true;
	});
	
	// soluciona problema de Internet explorer 7
	$('#enlaces').css('display','none');
	
	$('#buscar_textfield').focus(function(){
	    $(this).val('').css('color','#000');
	});
	
	// Se inicializa el fomulario para envio de mensaje
	$('#feedbackSendButton').click(function(){
		if( formValido( document.getElementById('feedbackForm') ) ) {
			enviaForm( document.getElementById('feedbackForm') );
		}
	});
    
    // Se impide la selección de texto (imágenes).
    $('#post-tabs, #mostrador').bind('selectstart select dblclick mousedown', function(){
        return false;
    });
    
    
    //$('.column_cat_title').css('float', 'left');
    
    var title_h = 0;
    var t_flag = false;
    $('.cat-title').each(function(){
        title_h = Math.max(title_h, $(this).outerHeight());
    });
    
    $('.cat-title').each(function(){
        if( $(this).outerHeight() < title_h ){
            $(this).addClass('one-line').children(':first');
            t_flag = true;
        }
    });
    
    if( t_flag ) {
        $('.cat-title').css('position', 'relative').height(title_h);
        $('.column_cat_title').css('float', 'left').css('position', 'absolute').each(function(){
            var w = (- $(this).width() / 2) + 'px' ;
            var h = (- $(this).height() / 2) + 'px';
            $(this).css('position', 'absolute').css('top', '50%').css('left', '50%').css('margin-top', h).css('margin-left', w);
        });
    }
    
});
