// JavaScript Document
var q,
	mid,
	modConfig,
	ajaxWorking = false,
	contador = 1,
	myURL = $(document).url();

$(document).ready(function() {
	q = $("#_mid").val();
	mid = q;
	modConfig = jQuery.parseJSON($("#_midConfig").val());
	//ak todo lo que puede ir en la intro y en el index
	$(".ampliar").colorbox();	
	$('#sliderPortada').nivoSlider({
		effect: 'slideInRight', // Specify sets like: 'fold,fade,sliceDown'
		slices: 5, // For slice animations
		boxCols: 8, // For box animations
		boxRows: 4, // For box animations
		animSpeed: 1000, // Slide transition speed
		pauseTime: 5000, // How long each slide will show
		startSlide: 0, // Set starting Slide (0 index)
		directionNav: false, // Next & Prev navigation
		directionNavHide: false, // Only show on hover
		controlNav: false, // 1,2,3... navigation
		controlNavThumbs: false, // Use thumbnails for Control Nav				
		keyboardNav: false, // Use left & right arrows
		pauseOnHover: false, // Stop animation while hovering
		manualAdvance: false, // Force manual transitions
		captionOpacity: 0.8, // Universal caption opacity
		prevText: 'Prev', // Prev directionNav text
		nextText: 'Next', // Next directionNav text
		beforeChange: function(){
			moverTextos();	
		}
	});
	$("#formNL").validationEngine().submit(function(event){event.preventDefault();}); 
	
	$("#btnEnviarNL").click(function(){
		if($("#formNL").validationEngine("validate")) {
			$("#formNL input").each(function(){$(this).attr("disabled","disabled");});
			$("#formNL .boxDerecha").fadeTo(250,.5);
			var sv=new Object();
			sv.mid="nl";
			sv.func="suscribe";
			sv.email = $("#mailNewsletter").val();
			sv.nombre = $("#nombreNewsletter").val();
			$.get("index.php",sv,function(data){
				try{console.debug(data);}catch(e){}	
				$("#formNL .boxDerecha").fadeTo(250,0,function(){
					$(this).html("<p>Registro realizado con éxito.</p>").fadeTo(250,1);	
				});
			},'json');
		}
	});
	$("#formNL input[type=text]").keydown(function(event) {
		if (event.keyCode == '13') $("#btnEnviarNL").click();
	});
	//
	/*--------------- MAIN SWITCH --------------------*/
	switch (q) {
		case "portada":
		break;
		case 'servicios':
			$('#acordeon h3').click(function(){
				if($(this).hasClass('abierto')){
					cerrarAcordeon();
					$(this).removeClass('abierto');
					$(this).children('span').html('+');
				}else{
					cerrarAcordeon();
					$(this).children('span').html('-');
					$(this).addClass('abierto');
					$(this).next('div').slideDown(500);
				}
			});
			if(myURL.attr("hash")!=undefined) {
				$("#"+myURL.attr("hash")).parent().click();
			}
		break;
		case "blog":
		
		break;
		case "contacto":
			$('#inputNombre').focus();
			$("#formContacto").validationEngine();
			$("#btnEnviar").click(function(){
				if(!onSend) {
					$("#btnEnviar").validationEngine("hideAll");
					onSend=true;
					if($("#formContacto").validationEngine("validate")) {
						$.post("sendForm.php",$("#formContacto").serialize(),function(data){
							if(data.error == "OK") {
								$("#formulario").slideUp(500);
								$("#gracias").delay(500).slideDown(200);
							} else {
								$("#btnEnviar").validationEngine("showPrompt","Int&eacute;ntelo m&aacute;s tarde por favor.");	
							}
							onSend=false;
						},'json');
					} else {
						onSend=false;	
					}
				}
			});			
		break;
	}
});

function moverTextos(){
	if(contador != 3){
		contador ++;
		$('#textosSlider').animate({marginLeft: '-=900px'}, 1000);	
	}else{
		contador = 1;
		$('#textosSlider').animate({marginLeft: '-=900px'}, 1000, function(){
				$('#textosSlider').css('margin-left', 0);
		});
	}
}
function cerrarAcordeon(){
	$('#acordeon').children('.detalleServicio').slideUp(500);
	$('#acordeon h3').children('span').html('+');
	$('#acordeon h3').removeClass('abierto');
}
/* ---------------------------------------- */
/* placeholder emulator */
var onSend = false;
(function($) {
	$.extend({
		placeholder : {
			settings : {
				focusClass: 'placeholderFocus',
				activeClass: 'placeholder',
				overrideSupport: false,
				preventRefreshIssues: true
			},
			debug : false,
			log : function(msg){
				if(!$.placeholder.debug) return;
				msg = "[Placeholder] " + msg;
				$.placeholder.hasFirebug ?
				console.log(msg) :
				$.placeholder.hasConsoleLog ?
					window.console.log(msg) :
					alert(msg);
			},
			hasFirebug : "console" in window && "firebug" in window.console,
			hasConsoleLog: "console" in window && "log" in window.console
		}

	});

    // check browser support for placeholder
    $.support.placeholder = 'placeholder' in document.createElement('input');

	// Replace the val function to never return placeholders
	$.fn.plVal = $.fn.val;
	$.fn.val = function(value) {
		$.placeholder.log('in val');
		if(this[0]) {
			$.placeholder.log('have found an element');
			var el = $(this[0]);
			if(value != undefined)
			{
				$.placeholder.log('in setter');
				var currentValue = el.plVal();
				var returnValue = $(this).plVal(value);
				if(el.hasClass($.placeholder.settings.activeClass) && currentValue == el.attr('placeholder')){
					el.removeClass($.placeholder.settings.activeClass);
				}
				return returnValue;
			}

			if(el.hasClass($.placeholder.settings.activeClass) && el.plVal() == el.attr('placeholder')) {
				$.placeholder.log('returning empty because it\'s a placeholder');
				return '';
			} else {
				$.placeholder.log('returning original val');
				return el.plVal();
			}
		}
		$.placeholder.log('returning undefined');
		return undefined;
	};

	// Clear placeholder values upon page reload
	$(window).bind('beforeunload.placeholder', function() {
		var els = $('input.' + $.placeholder.settings.activeClass);
		if(els.length > 0)
			els.val('').attr('autocomplete','off');
	});


    // plugin code
	$.fn.placeholder = function(opts) {
		opts = $.extend({},$.placeholder.settings, opts);

		// we don't have to do anything if the browser supports placeholder
		if(!opts.overrideSupport && $.support.placeholder)
		    return this;
			
        return this.each(function() {
            var $el = $(this);

            // skip if we do not have the placeholder attribute
            if(!$el.is('[placeholder]'))
                return;

            // we cannot do password fields, but supported browsers can
            if($el.is(':password'))
                return;
			
			// Prevent values from being reapplied on refresh
			if(opts.preventRefreshIssues)
				$el.attr('autocomplete','off');

            $el.bind('focus.placeholder', function(){
                var $el = $(this);
                if(this.value == $el.attr('placeholder') && $el.hasClass(opts.activeClass))
                    $el.val('')
                       .removeClass(opts.activeClass)
                       .addClass(opts.focusClass);
            });
            $el.bind('blur.placeholder', function(){
                var $el = $(this);
				
				$el.removeClass(opts.focusClass);

                if(this.value == '')
                  $el.val($el.attr('placeholder'))
                     .addClass(opts.activeClass);
            });

            $el.triggerHandler('blur');
			
			// Prevent incorrect form values being posted
			$el.parents('form').submit(function(){
				$el.triggerHandler('focus.placeholder');
			});

        });
    };
})(jQuery);

