/*INICIALIZAR ------------------------------------------------------------------------------------*/
//Inicializar página (en el array ready_callbacks se pueden aplicar callbacks)
$(function() {
	//
	$('#context_menu_right').html( $('#context_menu_left').html() );

	//Funciones de resize (máxima prioridad)
	window_resize_init();

	initForms();

	//Iniciar header
	$('#select_lang').click(function() {
	    var elem = $(this);
	    if(elem.attr('rel') == 'opened'){
			elem.find("#selector_lang").removeClass('selected');
			elem.attr('rel', 'closed');
		}
		else{
			elem.find("#selector_lang").addClass('selected');
			elem.attr('rel', 'opened');
		}
		$('#select_lang_dropdown').toggle();
	});

	//iniciar los links voip popup
	$('a.link_voip').click(function(){
	window.location.href=rel_voip;
	  //var rel = $(this).attr('rel');
	  /*$.fn.colorbox({
			'href':rel_voip,
			width:650,
			height:590,
			onComplete: function(){
			  initForms();
				$('div.popup #privacidad').click(function(){initPrivacidad();});
				return false;
			}
		});*/
	});

	var account_opened = 0;
	var link_text = $('.link_area_cliente.and_logout').text();
	$('.link_area_cliente').click(function() {
		var elem = $(this);
	  if(!$('#area_cliente_dropdown').length)window.location.href = area_cliente_link;
		if(account_opened == 0){
		    $("#body").before("<div id='loading'></div>");
    		if(error_login) var height = 310;
	 		else var height = 281;
	 		$('#area_cliente_dropdown_content').show();
			$('#area_cliente_dropdown').animate(
				{'height': height+'px'}, 500,
				function(){
					$('.link_area_cliente.and_logout').addClass('close').text(cerrar);
	   			}
			);
			$('#select_lang').css('z-index', '1');
			
			account_opened = 1;
			
		}
	  else{
	    	$('#area_cliente_dropdown').animate(
				{'height': '0px'}, 500,
				function(){
				    $('#select_lang').css('z-index', '3');
				    $('#area_cliente_dropdown_content').hide();
				   	$('.link_area_cliente.and_logout').removeClass('close').text(link_text);
				   	$("#loading").remove();
		    	}
			);
		    account_opened = 0;
		    
		}
	});
	if(login_result.length)$('#area_cliente').click();

	//Desplegable menú lateral
	$('#menu a.l1').click(function() {
		var nextitem = $(this).next();
		if (nextitem.hasClass('submenu')) { 
			$(this).next().slideToggle();
			return false;
		}
	});
	
	$("select.como_conocio").change(function(){
		var option = $(this)[0].selectedIndex;
		option = $(this)[0].options[option];
		if($(option).attr('rel') == 'otro') $(this).parent().find('input.otro_valor').show();
		else $(this).parent().find('input.otro_valor').hide();
	});
	
	$("div.how_met_us input.checkbox").click(function(){
	    var elem = $(this);
	    if(elem.is(':checked') && elem.val().toLowerCase() == 'otro') elem.parent().find('.otro_valor').show();
		else elem.parent().find('.otro_valor').hide();
	});

	//Ejecutar callbacks pendientes
	for (var i=0; i<ready_callbacks.length; i++) {
		//try {
			ready_callbacks[i]();
		//} catch(ex) {
		//}
	}
});
$(window).load(window_resize);

/*function initPrivacidad(){
	$('div.popup').hide();
	$('div#politica_privacidad').show();
	$("#cboxClose").unbind('click').click(function(){initPopup();});
}*/

/*function initPopup(){
	$('div#politica_privacidad').hide();
	$('div.popup').show();
	$("#cboxClose").unbind('click').click(function(){$.fn.colorbox.close();});
}*/

function initForms(){
	$("form.autovalidate").each(function(){
	    var formulario = $(this);
		formulario.validate({
			errorPlacement: function(error, element) {
    			if(element.attr('type') == "checkbox"){
    			    element.closest("div").addClass("error");
				}
			},
			hideErrors: function(){}
		});
	});
	
	$("form.formulario input.required[type!=password], form.formulario input.required[type!=file]").each(function(){
	    var elem = $(this);
	    elem
			.focus(function(){
		  	    if(elem.val() == campo_obligatorio) elem.val('');
			})
			.blur(function(){
				if( !elem.val()) elem.val(campo_obligatorio);
			});
        if( !elem.val()) elem.val(campo_obligatorio);
	});

}

//pads left
function lpad(str, padString, length){
	str = str.toString();
	while (str.length < length)
	    str = padString + str;
	return str;
}

//pads right
function rpad(str, padString, length){
	str = str.toString();
	while (str.length < length)
	    str = str + padString;
	return str;
}

/* MESAGES -------------------------------------------------------------------*/
var Growl = {
	getDock: function(id, rebuild) {
		var instance = document.getElementById(id);
		if(!instance || rebuild) {
		  	instance = $('<div id="'+id+'" class="growl"></div>');
		  	$('body').append(instance);
		} else {
		  	instance = $(instance);
		}
		return instance;
	},
	showModal: function(message, timeout) {
		var div = $('<div>'+message+'</div>');
		var container=Growl.getDock('growlModal').html('').append(div).show();
		var width = div.width();
		var height = div.height();
		div.css('marginLeft',-width/2).css('marginTop',-height/2);
		if (timeout) setTimeout(function() { container.hide(); },timeout);
	},
	closeModal: function() {
		Growl.getDock('growlModal').hide();
	},
	notify: function(message, msgClass, container, timeout) {
		if (!msgClass) msgClass='info'; //info || error || complete
		if (!container) container=Growl.getDock('growlDock');
		if (!timeout) timeout=2000;
		var _msg = $('<div class="box_'+msgClass+'">'+message+'</div>').appendTo(container);
		setTimeout(function() { _msg.fadeOut('slow', function() { $(this).remove(); }); },timeout);
	}
};

/*SMALL GALLERY ----------------------------------------------------------------------------------*/
$.fn.small_gallery = function(options){
	var op = {
		'duration': 8000,
		'autoplay': true,
		'textfield': false
	};

	if (options) op = $.extend(op, options);

	return this.each(function() {
		var gallery = $(this);
		var images = gallery.find('img.grafic');
		var paginate = gallery.find('div.paginate');
		var galleryTimer;
		var currentPage = -1;
		
		function setPage(page) {
			if (currentPage==page) return false;
			var img = images.fadeOut().eq(page).fadeIn();
			paginate.find('a').removeClass('current').removeClass('selected');
			paginate.find('a').slice(0,page+1).addClass('selected');
			paginate.find('a').eq(page).addClass('current');
			currentPage = page;
			
			//actualizar pie de foto
			if (op.textfield) {
			    gallery.parent().find(op.textfield).text(img.attr('alt'));
			}
			
			return false;
		}	
		function play() {
			var page = currentPage+1;
			if(page >= images.length) page = 0;
			setPage(page);
		}
		
		gallery.find('div.prev').click(function(){
			var page = currentPage-1;
			if(page < 0) page = images.length-1;
			setPage(page);
			clearInterval(galleryTimer);
			return false;
		});
		gallery.find('div.next').click(function(){
			var page = currentPage+1;
			if (page>=images.length) page=0;
			setPage(page);
			clearInterval(galleryTimer);
			return false;
		});

		var html = '';
		for (var i=0; i<images.length; i++) {
			var className = 'page';
			if (i==0) className += ' first';
			if (i==images.length-1) className +=' last';
		    html += '<a href="javascript:;" class="'+className+'" rel="'+i+'" title="'+images.eq(i).attr('alt')+'"><span>'+(i+1)+'</span></a>';
		}
		html += '<a href="javascript:;" class="pause" title="Pause"><span>pause</span></a>';
		html += '<a href="javascript:;" class="play" title="Play"><span>play</span></a>';

		paginate.html(html);
		//paginate.find('a').tinyTips({'position':'right'});
		paginate.find('a.play').click(function() {
			galleryTimer = setInterval(play, op.duration);
			return false;
		});
		paginate.find('a.pause').click(function() {
			clearInterval(galleryTimer);
			return false;
		});
		paginate.find('a.page').click(function() {
			setPage(this.getAttribute('rel'));
			return false;
		});

		setPage(0);
		if (op.autoplay) paginate.find('a.play').click();
	});
}

/*ACORDEON ---------------------------------------------------------------------------------------*/
$.fn.acordeon = function(options){
	var op = {
		'duration': 'fast',
		'onComplete': false
	};
	if (options) op = $.extend(op, options);

	return this.each(function() {
		var acordion = $(this);
		acordion.find('a.acordeon_trigger').click(function() {
			if ($(this).hasClass('selected')) return false;
			var id = this.getAttribute('href').replace(/^[^#]+/, ''); 
			
			acordion.find('div.acordeon_content').slideUp(op.duration);
			acordion.find('a.acordeon_trigger').removeClass('selected');
			acordion.find('a.acordeon_trigger input').hide();
			$(id).slideDown(op.duration);
			$(this).addClass('selected');		  
			$(this).children('input').show();
			return false;
		});

		if (op.onComplete && typeof op.onComplete == 'function') {
			op.onComplete();
		} else {
			acordion.find('a.acordeon_trigger').eq(0).click();
		}

		
		if (op.complete && typeof op.complete == 'function') {
			op.complete();
		}

	});
}

/*EXPANDABLE TEXT --------------------------------------------------------------------------------*/
$.fn.expandableText = function(options) {
	var op = {
	    text_more: '[+]',
	    text_less: '[-]',
	    collapsable: true
	};
	if (options) op = $.extend(op, options);

	return this.each(function() {
		var elem = $(this).addClass('expandable-text-item');
		var contents = elem.find('p, ul');
		
		var total = contents.length;
		if (total<2) return;

		for (i=0;i<total;i++) {
		    if (i==0) {
			    contents.eq(i)
					.addClass('expandable-text-first')
					.append('<br /><a href="javascript:;" class="expandable-text-show">' + op.text_more + '</a>')
					.after('<div class="expandable-text-more"></div>');
			} else {
			    contents.eq(i).appendTo( elem.find('div.expandable-text-more') );
			}
		}

		if (op.collapsable) {
			$('div.expandable-text-more', elem)
				.append('<p><a href="javascript:;" class="expandable-text-hide">' + op.text_less + '</a></p>')
                .find('a.expandable-text-hide').click(function(){
				    $(this).closest('div.expandable-text-more').slideUp(function(){
				    	$('a.expandable-text-show', elem).show();
					});
				    return false;
			});
		}

		$('div.expandable-text-more', elem).hide();
		$('a.expandable-text-show', elem).click(function(){
		    $(this).hide().closest('div.expandable-text-item').find('div.expandable-text-more').slideDown();
		    return false;
		});

	});
}

/*TABS -------------------------------------------------------------------------------------------*/
$.fn.tabs = function(options) {
	var op = { };
	if (options) op = $.extend(op, options);
	
	return this.each(function() {
		var tabs = $(this);
		tabs.find('ul.triggers a').click(function() {
			if ($(this).hasClass('selected')) return false;
			var id = this.getAttribute('href').replace(/^[^#]+/, ''); 
			
			tabs.find('div.tab').hide();
			tabs.find('ul.triggers a').removeClass('selected');
			$(id).show();
			$(this).addClass('selected');		  
			return false; 	
		});
		tabs.find('ul.triggers a:last').click();
	});
}

/*MINI TABS --------------------------------------------------------------------------------------*/
function miniTabsInit(){
	$('div.miniTabs div.miniTabName a').click(function(){
	  var rel = $(this).attr('rel');
	  if ( $("#miniTab_content_"+rel).hasClass('miniTab_invisible')){

	    $('div.miniTabs div.miniTab_content').addClass('miniTab_invisible').hide();

		  $("#miniTab_content_"+rel).show().removeClass('miniTab_invisible');

		  $('div.miniTabs div.miniTabName').removeClass('selected');
		  $(this).closest('div.miniTabName').addClass('selected');
		}
		return false;
	}).eq($('div.miniTabs div.miniTabName a').length-1).click();
}

/*WINDOW REXIZE ----------------------------------------------------------------------------------*/  
var resize_right_box;
var resize_right_box_top;
var resize_images;
var resize_images_size = false;
function window_resize_init() {
	resize_right_box = $('#right');
	resize_right_box_top = parseInt(resize_right_box.css('top'));
	resize_images = resize_right_box.find('img.bg');

    $(window).resize(window_resize);
    if (!resize_fixed) $(window).scroll(window_scroll);
    
    var first_image = resize_images.eq(0);
   	var width = first_image.width();
	if (width) {
		resize_images_size = [ width, first_image.height() ]; 
		window_resize();
	} else { 
	    first_image.load(function() {
	    	var t = $(this);
			resize_images_size = [ t.width(), t.height() ]; 
			window_resize();		
		});
	}
};

function window_resize() {
	var body_width = document.body.offsetWidth;
	var body_height = f_clientHeight();
	
	//Context menu
	if (body_width<1440) {
		$('#context_menu_right').hide();
		$('#context_menu_left').show();
	} else {
		$('#context_menu_right').show();
		$('#context_menu_left').hide();
	}
	
	//iconas redes sociales
	if (!resize_fixed) {
		if (body_width<1440){
		    $("#right div.copyright div.social_networks").css('clear', 'both').css('float','right').css('margin-bottom', '10px');
		    $("#right div.copyright div.links_imoi").css('clear', 'both');
		    $("#right div.copyright div.links_imoi span").css('border-left', '0px');
		    $("#right div.copyright").css('width', 'auto');
		    if($("img.bg").length) $("#right div.copyright").css('right',0);
		}
		else{
		    $("#right div.copyright div.social_networks").css('clear', 'none').css('float','left').css('margin-bottom', '0px');
		    $("#right div.copyright div.links_imoi").css('clear', 'none');
		    $("#right div.copyright div.links_imoi span").css('border-left', '1px solid #D9CFB3');
		    if($("img.bg").length) $("#right div.copyright").css('right',0);
		}
	}

	if (resize_fixed) {
		var w = resize_right_box.width();
		var h = resize_right_box.height();
	} else { 
		var w = $('#content').width()+256;
		var w_content = w;

		w = body_width - w;
		if (w<310) w = 310;
		if(resize_right_box.find("img.bg").length || resize_right_box.find("#context_menu_right").css('display') != "none") resize_right_box.width(w);
		else{
		    if(!resize_right_box.find("img.bg").length || resize_right_box.find("#context_menu_right").css('display') == "none"){
				resize_right_box.width(0);
				$("#content").css('margin-right','0px');
			}
		}
		//.width(body_width+w)
		
		var h = body_height - resize_right_box_top;
		//if(resize_right_box.find("#context_menu_right").css('display') != "none")
		resize_right_box.height(h);
	}
	
      
	//Imagenes laterales
	if ( resize_images_size ) {
	    var w_lateral = w;

	    var w_ratio = w / resize_images_size[0];
		var h_ratio = h / resize_images_size[1];
		if (w_ratio>h_ratio) { h = resize_images_size[1]*w_ratio; }
		else { w = resize_images_size[0]*h_ratio; }
	    resize_images.css({width: w+'px',height: h+'px', top: '0px'});
    }else var w_lateral = 0;
    
    if(body_width-w_lateral == 215) w_lateral=0;

    //imagen cabecera
    $("#header div.logo_box").width(body_width-w_lateral);
    
    /*var padding_left = $("#content").css('padding-left');
    var width_content = parseInt($("#content").width()) + parseInt(padding_left.substring(padding_left.length, -2));*/

	var body_tag = document.getElementsByTagName("body");
	var html_tag = document.getElementsByTagName("html");

    if(body_width < 1024 ){
		/*var width_px = body_width-width_content;
		$("#right").css('position', 'absolute');
        $("#right").width(width_px);
        $("#content")[0].style.marginRight = (width_px)+'px';*/

        if($.browser.msie){
			body_tag[0].style.width = '100%';
			html_tag[0].style.width = '100%';
		}
		else{
	        body_tag[0].style.minWidth = 'inherit';
			html_tag[0].style.minWidth = 'inherit';
        }
	}
	else{
		if($.browser.msie){
		    body_tag[0].style.width = '100%';
			html_tag[0].style.width = '100%';
		}
		else{
		    body_tag[0].style.minWidth = 'inherit';
			html_tag[0].style.minWidth = 'inherit';
		}
	}
	
	
	var width_content_tr = $("div.tratamientos div.acordeon_content").outerWidth();
	if(width_content_tr<722){
	    $("div.tratamientos div.info").width('100%');
        $("div.tratamientos div.more_info").width('100%');
	}
	else{
	    $("div.tratamientos div.info").width(410);
		$("div.tratamientos div.more_info").width(270);
	}
	/*console.log($("div.tratamientos div.more_info"));
	$("div.tratamientos div.more_info div.text").each(function(){
	    var par = $(this).parent();
	    console.log(par.outerWidth());
		//width($("div.tratamientos div.more_info").outerWidth()-(13*2));
	});*/
	
	var width_content_tr = $("div.contacto div.acordeon_content").outerWidth();
	if(width_content_tr<722){
	    //$("div.contacto div.info").width('100%');
        $("div.contacto div.more_info").width('100%');
	}
	else{
	    //$("div.contacto div.info").width(410);
		$("div.contacto div.more_info").width(270);
	}
	//$("div.contacto div.more_info div.text").width($("div.contacto div.more_info").outerWidth()-(13*2));
	
	
	var width_content_noticias = $("div.noticias div.intro.noticias.noticia").outerWidth();
	if(width_content_noticias <= 691){
	    $("div.noticias div.intro.noticias.noticia div.new_info").width('100%').css('margin-bottom', '20px');
	    $("div.noticias div.intro.noticias.noticia div.new_moreinfo").width('100%').css('max-width', '100%');
	}
	else{
	    $("div.noticias div.intro.noticias.noticia div.new_info").width(140).css('margin-bottom', '0px');
	    $("div.noticias div.intro.noticias.noticia div.new_moreinfo").width('553px').css('max-width', '553px');
	}
	
	var width_content_noticias = $("div.noticias div.intro.noticias").outerWidth();
	if(width_content_noticias <= 306){
	    $("div.noticias div.intro.noticias div.subtitulo").width('100%').css('margin-bottom', '20px').css('margin-left', '0px').css('clear', 'both');
	    $("div.noticias div.intro.noticias div.text").width('100%').css('margin-bottom', '20px').css('margin-left', '0px').css('clear', 'both');
	}
	else{
	    $("div.noticias div.intro.noticias div.subtitulo").width('auto').css('margin-bottom', '20px').css('margin-left', '159px').css('clear', 'none');
	    $("div.noticias div.intro.noticias div.text").width('auto').css('margin-bottom', '20px').css('margin-left', '159px').css('clear', 'none');
	}
	
	var width_content_responsabilidad = $("div.responsabilidad_social").outerWidth();
	if(width_content_responsabilidad <= 903){
	    $("div.responsabilidad_social div.more_info").css('padding-top', '0px');
	    $("div.responsabilidad_social div.more_info img").css('float', 'left');
	}
	else {
		$("div.responsabilidad_social div.more_info").css('padding-top', '15px');
		$("div.responsabilidad_social div.more_info img").css('float', 'inherit');
	}
	
	$('div.destinos div.mini_tabs_content').each(function(){
	    var elem = $(this);
	    var height = elem.find('div.photos img.photo').eq(0).height();
	    elem.find('div.photos').css('height', height+'px');
	});
	
	
	if($("div.instalaciones").length){
		var width_content_instalaciones = $("div.instalaciones").outerWidth();
		if(width_content_instalaciones <= 993) $("div.copyright").hide();
		else $("div.copyright").show();
	}
	
    if($("img.bg").length){
	    var width_right = $("#right").css('width').split('px');
	    //if(width_right[0] == 310){
	        var width_right_rel = $("div.right_rel").css('width').split('px');
	        var width_image = $("img.bg").css('width').split('px');
	        width_image = width_image[0] - width_right_rel[0];
	        //width_image = width_image[0];
	        width_image = (width_image/2);
	        $("img.bg").css('left',-(width_image));
		/*}
		else{
		  $("img.bg").css('left', 0);
		}*/
	}
	 

	
	
    /*if (w_lateral==310) {
        $('#content').css('margin-right', '0px');
        $('#content').css('width', $('#content').width()-w);
        resize_right_box.width(w);
        
        $('#header').css('position', 'relative');
        resize_right_box.css('position', 'relative');
	}
	else{
	}*/
	
    //if(w_content<310) w_content = 310;
    /*console.log(w_content);
    console.log(w);
    if (body_width<1440) $('#content').css('max-width',w_content-w);
	resize_right_box.css('left',body_width-w);
	resize_right_box.width(w);*/
    
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

/*WINDOW SCROLL ----------------------------------------------------------------------------------*/
function window_scroll() {
	var top = f_scrollTop(); 
	//resize_right_box.css('top',top);
	//window_resize();
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	if (n_win) return n_win;
	var n_result = n_win ? n_win : 0;
	var n_result = 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

