(function ($) {


jQuery.preloadCssImages = function(settings){
	settings = jQuery.extend({
		statusTextEl: null,
		statusBarEl: null,
		errorDelay: 999, // handles 404-Errors in IE
		simultaneousCacheLoading: 2
	}, settings);
	var allImgs = [],
		loaded = 0,
		imgUrls = [],
		thisSheetRules,
		errorTimer;

	function onImgComplete(){
		clearTimeout(errorTimer);
		if (imgUrls && imgUrls.length && imgUrls[loaded]) {
			loaded++;
			if (settings.statusTextEl) {
				var nowloading = (imgUrls[loaded]) ?
					'Now Loading: <span>' + imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length - 1] :
					'Loading complete'; // wrong status-text bug fixed
				jQuery(settings.statusTextEl).html('<span class="numLoaded">' + loaded + '</span> of <span class="numTotal">' + imgUrls.length + '</span> loaded (<span class="percentLoaded">' + (loaded / imgUrls.length * 100).toFixed(0) + '%</span>) <span class="currentImg">' + nowloading + '</span></span>');
			}
			if (settings.statusBarEl) {
				var barWidth = jQuery(settings.statusBarEl).width();
				jQuery(settings.statusBarEl).css('background-position', -(barWidth - (barWidth * loaded / imgUrls.length).toFixed(0)) + 'px 50%');
			}
			loadImgs();
		}
	}

	function loadImgs(){
		//only load 1 image at the same time / most browsers can only handle 2 http requests, 1 should remain for user-interaction (Ajax, other images, normal page requests...)
		// otherwise set simultaneousCacheLoading to a higher number for simultaneous downloads
		if(imgUrls && imgUrls.length && imgUrls[loaded]){
			var img = new Image(); //new img obj
			img.src = imgUrls[loaded];	//set src either absolute or rel to css dir
			if(!img.complete){
				jQuery(img).bind('error load onreadystatechange', onImgComplete);
			} else {
				onImgComplete();
			}
			errorTimer = setTimeout(onImgComplete, settings.errorDelay); // handles 404-Errors in IE
		}
	}

	function parseCSS(sheets, urls) {
		var w3cImport = false,
			imported = [],
			importedSrc = [],
			baseURL;
		var sheetIndex = sheets.length;
		while(sheetIndex--){//loop through each stylesheet

			var cssPile = '';//create large string of all css rules in sheet

			if(urls && urls[sheetIndex]){
				baseURL = urls[sheetIndex];
			} else {
				var csshref = (sheets[sheetIndex].href) ? sheets[sheetIndex].href : 'window.location.href';
				var baseURLarr = csshref.split('/');//split href at / to make array
				baseURLarr.pop();//remove file path from baseURL array
				baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
				if (baseURL) {
					baseURL += '/'; //tack on a / if needed
				}
			}
			if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){
				thisSheetRules = (sheets[sheetIndex].cssRules) ? //->>> http://www.quirksmode.org/dom/w3c_css.html
					sheets[sheetIndex].cssRules : //w3
					sheets[sheetIndex].rules; //ie
				var ruleIndex = thisSheetRules.length;
				while(ruleIndex--){
					if(thisSheetRules[ruleIndex].style && thisSheetRules[ruleIndex].style.cssText){
						var text = thisSheetRules[ruleIndex].style.cssText;
						if(text.toLowerCase().indexOf('url') != -1){ // only add rules to the string if you can assume, to find an image, speed improvement
							cssPile += text; // thisSheetRules[ruleIndex].style.cssText instead of thisSheetRules[ruleIndex].cssText is a huge speed improvement
						}
					} else if(thisSheetRules[ruleIndex].styleSheet) {
						imported.push(thisSheetRules[ruleIndex].styleSheet);
						w3cImport = true;
					}

				}
			}
			//parse cssPile for image urls
			var tmpImage = cssPile.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename" / '"' for opera-bugfix
			if(tmpImage){
				var i = tmpImage.length;
				while(i--){ // handle baseUrl here for multiple stylesheets in different folders bug
					var imgSrc = (tmpImage[i].charAt(0) == '/' || tmpImage[i].match('://')) ? // protocol-bug fixed
						tmpImage[i] :
						baseURL + tmpImage[i];

					if(jQuery.inArray(imgSrc, imgUrls) == -1){
						imgUrls.push(imgSrc);
					}
				}
			}

			if(!w3cImport && sheets[sheetIndex].imports && sheets[sheetIndex].imports.length) {
				for(var iImport = 0, importLen = sheets[sheetIndex].imports.length; iImport < importLen; iImport++){
					var iHref = sheets[sheetIndex].imports[iImport].href;
					iHref = iHref.split('/');
					iHref.pop();
					iHref = iHref.join('/');
					if (iHref) {
						iHref += '/'; //tack on a / if needed
					}
					var iSrc = (iHref.charAt(0) == '/' || iHref.match('://')) ? // protocol-bug fixed
						iHref :
						baseURL + iHref;

					importedSrc.push(iSrc);
					imported.push(sheets[sheetIndex].imports[iImport]);
				}


			}
		}//loop
		if(imported.length){
			parseCSS(imported, importedSrc);
			return false;
		}
		var downloads = settings.simultaneousCacheLoading;
		while( downloads--){
			setTimeout(loadImgs, downloads);
		}
	}
	parseCSS(document.styleSheets);
	return imgUrls;
};



    $.fn.vAlign = function() {
    return this.each(function(i){
    var h = $(this).height();
    var oh = $(this).outerHeight();
    var mt = (h + (oh - h)) / 2;
    $(this).css("margin-top", "-" + mt + "px");
    $(this).css("top", "50%");
    $(this).css("position", "absolute");
    });
    };
    })(jQuery);
    (function ($) {
    $.fn.hAlign = function() {
    return this.each(function(i){
    var w = $(this).width();
    var ow = $(this).outerWidth();
    var ml = (w + (ow - w)) / 2;
    $(this).css("margin-left", "-" + ml + "px");
    $(this).css("left", "50%");
    $(this).css("position", "absolute");
    });
    };
    })(jQuery);

    $(document).ready(function() {

    $.preloadCssImages();
    $(".sliderfrase").vAlign();
    $(".sliderfrase, .contenidos").hAlign();
    $(".sliderfrase").delay(100).fadeIn(400).delay(2500).fadeOut(400);
    $("#bienvenidos #slidercont").delay(3000).fadeIn("400");

function mycarousel_initCallback(carousel) {

    jQuery('.btn_forw').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#mycarousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
    jQuery('.btn_infos, .conoce_btn').bind('click', function() {
        carousel.scroll(1);
    });
};


    $('#infografias').jcarousel({
        scroll: 1,

        visible: 1,
        wrap: 'last',
        initCallback: mycarousel_initCallback

    });
    $('.btn_infos, .conoce_btn').click( function() {
        $("#wrapinfos").css({visibility: "visible"}).animate({height: "100%"}, 500 );
        return false;
    });
    $('.jcarousel-item .cerrar').click( function() {
        $("#wrapinfos").animate({height: "0"}, 500 );
        return false;
  
    });

});


function elements_position(){
	//Vars
	var window_width = $(window).width();
	var window_height = $(window).height();
	var wrap_xpos = $('#wrap').offset().left;
	var wrap_ypos = $('#wrap').position().top;
	var slider_xpos = $('#slidercont').offset().left + $('#slidercont').width(); 

        if(window_height > 590){
          $(".jcarousel-item").height(window_height - 50);
        }else{
          $(".jcarousel-item").height(540);
        }


	//Siguenos
	if(window_width > $('#wrap').width()+ 130){
		$('#siguenos').css('left', window_width - $('#siguenos').width() + 60);
	}else{
		$('#siguenos').css('left', slider_xpos - 45);
	}
	if(window_width > $('#wrap').width()+ 130){
		$('#tudu').css('left', window_width - $('#siguenos').width());
	}else{
		$('#tudu').css('left', slider_xpos - 110);
	}
	//Footer

	if(window_height > $('#sidebar').height() + 50){
		$('#footer').css('top', window_height -  ($('#creditos').height()+10));
	}else{
		$('#footer').css('top', $('#sidebar').height() + 50);
	}
	$('#footer').css('left', wrap_xpos + 10);
	
	//Te gusta poco
	// if(window_width > $('#wrap').width()+ 200){
	//	$('#me_gusta').css('left', window_width - $('#me_gusta').width());
	// }else{
        // $('#me_gusta').css('left', slider_xpos - 130);
	// }
        
	if(window_height > $('#sidebar').height() + 40){
		$('#tudu').css('top', window_height - 120);
	}else{
		$('#tudu').css('top', $('#sidebar').height() + 50);
	}
}

//Function slide menu
function slide_menu(){

	$('#slider_menu li:first').addClass('first_child');
	
	$('#slider_menu').mouseenter(function(){
		$('#slider_menu').animate({height: "128px"}, 200);
                }).mouseleave(function(){
                $('#slider_menu').animate({height: "40px"}, 200);
        });
        $('#slider_menu li:odd, #slider_menu li:last').mouseenter(function(){
		$(this).children('a').addClass('hover');
                }).mouseleave(function(){
                $(this).children('a').removeClass('hover');
        });
        $('.randomize').mouseenter(function(){
		$(this).addClass('hover');
                }).mouseleave(function(){
                $(this).removeClass('hover');
        });
         $('.randomize').click(function(){
		location.reload();
                return false;
        });
 }

//Validate email
function validate_mail(ele) {
   var reg = /^([A-Za-z0-9\'_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = $(ele).val();

   if(address.search(reg) == -1){
		return false;
   }else{
   		return true;
   }
}

function randomize(){
	//Aqui va el randomize
	 location.reload();
}
	 

var members_pos = new Array(
        '0 880px',
	'0 800px',
	'0 720px',
	'0 640px',
	'0 560px',
	'0 480px',
	'0 400px',
	'0 320px',
	'0 240px',
	'0 160px',
	'0 80px',
	'0 0'
);
function move_members_photo(){

	//Agrego las funcinalidades
        $("#team_members li .member_hover").click(function(){
                         $(this).hide();
                        $('#team_members li .member_photo').not(this).each(function(inn, elem){
                            $(elem).animate({'backgroundPosition':members_pos[inn], 'height': '200px'});
                            });
                        $(this).next().animate({'backgroundPosition':'0 880px', 'height': '200px'});
                        $("#team_members li").css("height","80px").removeClass('active');
			var alto = 200 + $(this).next().next().outerHeight();
			$(this).parent('li').animate({'height': alto}).addClass('active');


		});
	$('#team_members li .member_photo').each(function(index, ele){
		$(this).css('background-position', members_pos[index]);
		$(this).click(function(){
			$(this).animate({'backgroundPosition':'0 880px', 'height': '200px'});
		
			var alto = 200 + $(this).next().outerHeight();
			$(this).parent('li').animate({'height': alto}).addClass('active');
			
			var actual = $('#team_members li .member_photo').index($(this));
			$('#team_members li .member_photo').each(function(inn, elem){
				//Hide others elements
				if(inn != actual){ 
					$(elem).animate({'backgroundPosition':members_pos[inn], 'height': '200px'});
					$(elem).parent('li').animate({'height': '80px'}).removeClass('active');
				}
			});
		});
	});
	
	//Funcion para cerrar
	$('#team_members .cerrar').click(function(evt){
		$('#team_members li .member_photo').each(function(inn, elem){
		$(elem).animate({'backgroundPosition':members_pos[inn], 'height': '200px'});
		});
		$(this).parents('li').animate({'height': '80px'}).removeClass('active');
		
		evt.preventDefault();
		evt.stopPropagation();
	});
}

$(document).ready(function(){
    
       $('a[rel*=external]').click( function() {
        window.open(this.href);
        return false;
    });

	elements_position();
	slide_menu();	
	move_members_photo();
	
	
	//Items
        $(".cl_desc").hover(function(){

                $(this).toggleClass('inactive');
	});
	$('#clientes li').hover(function(){
				$(this).find('.imagen').hide();
			},
			function(){
				$(this).find('.imagen').show();
			}
		);


		$('#blog li, #home li').hover(function(){
					$(this).find('.descripcion').hide();
				},
				function(){
					$(this).find('.descripcion').show();
				}
			);

                $("#team_members li").hover(function(){
					$(this).not('.active').find('.member_hover').show();
				},
				function(){
					$(this).find('.member_hover').hide();
				}
			);


		//Seguir miembro
		$('.seguir_btn').each(function(index, ele){
			$(ele).hoverIntent(
				function(){
					$(ele).parents('p').next('ul').fadeIn();
					$(ele).addClass('btn_active');
				},
				function(){
					//release
				}
			);
		});
		$('.seguir').hoverIntent(
			function(){},
			function(){$(this).fadeOut();}
		);
		
		
		//Colaboradores
                $('#colaboradores #contenido .items li').hover(function(){
					$(this).find('.member_photo').hide();
				},
				function(){
					$(this).find('.member_photo').show();
				}
			);


        $('.etiquetas a').hoverIntent(
			function(){$(this).addClass('active');},
			function(){$(this).removeClass('active')
        });

	//Siguenos
	$('#siguenos .btn_infos a').hoverIntent(
		function(){$(this).addClass('active').animate({'height' : 133	});	},
		function(){$(this).animate({'height': 20},100 ).removeClass('active');	}
	);
        $('#siguenos .facebook a,#siguenos .twitter a, #siguenos .youtube a, #siguenos .linkedin a ').hoverIntent(
		function(){$(this).addClass('active').animate({'height' : 79	});	},
		function(){$(this).animate({'height': 20},100 ).removeClass('active');	}
	);
	
	//Compartir proyectos
	$('.compartir').hoverIntent(
		function(){
			$(this).first().children().nextAll().fadeIn();
		},
		function(){
			$(this).first().children().nextAll().fadeOut();
		}
	);
	
	//Formulario
	$('.submit_form').click(function(evt){
		var valida = true;
		//Valido nombre
		if($('#nombre').val() == ''){
			$('#nombre').css('borderColor', '#792d90');
			valida = false;
		}else{
			$('#nombre').css('borderColor', '#ccc');
		}
		
		//Valido email
		if(!validate_mail('#email')){
			$('#email').css('borderColor', '#792d90');
			valida = false;
		}else{
			$('#email').css('borderColor', '#ccc');
		}
		
		//Valido comentario
		if($('#comment').val() == ''){
			$('#comment').css('borderColor', '#792d90');
			valida = false;
		}else{
			$('#comment').css('borderColor', '#ccc');
		}
		
		if(valida){
			//Send form
			document.getElementById('form-contacto').submit();
		}else{
			return false;
		}

		
		evt.stopPropagation();
		evt.preventDefault();
	});

});

$(window).resize(function() {
	elements_position();
});

