var num_img = 0;
var images_array = new Array;

function initEmployees(){
	$('img','.employee_images').eq(0).css('display','block');
	$('span','.employee_name').eq(0).css('display','block');
	$('.employee','.employee_datas').eq(0).css('display','block');
}

function preloadImgs(){
	$('img').each(function(index){
		num_img++;
		images_array[num_img] = new Image();
		images_array[num_img].src = $(this).attr('src');
		/*imgcode = '<img src="'+$(this).attr('src')+'" alt="" />'
		$('.imgCache').append(imgcode);*/
	});

	$('div').each(function(index){
		if($(this).css('backgroundImage') != 'none'){
			num_img++;
			urlimg = $(this).css('backgroundImage').match(/url\((['"])(.+?)\1\)/);
			images_array[num_img] = new Image();
			if(urlimg != null){
				images_array[num_img].src = urlimg[2];
			}
		}
	});
}

function preloadTxt(){
	curtxt = $('#preloader_content .center_container span').text();
	if(curtxt == 'Loading...'){
		$('#preloader_content .center_container span').text('Loading...');
	} else if(curtxt == 'Loading OSP...'){
		$('#preloader_content .center_container span').text('BassMedics...');
	} else if(curtxt == 'las cuentas...'){
		$('#preloader_content .center_container span').text("Rejuvenade...");
	} else if(curtxt == "Welcome to Outdoor Specialty Products..."){
		$('#preloader_content .center_container span').text('bassmedics.com is being loaded...');
	}
}

setInterval("preloadTxt()",2500);

function replaceEmails(){
	// Se buscando los tag de tipo SPAN y de class CHANGE, que contienen los emails a reemplazar
	$('span.mail').each(function() {
		//itemClass = $(this).attr('title');
		itemMail = $(this).text();
		// Reemplaza " at " por la "@"
		address = itemMail.replace(/ at /g,'@');
		// Reemplaza " dot " por el "."
		address = address.replace(/ dot /g,'.');

		prevItem = $(this).prev();
		$(this).remove();
		// Creacion del nuevo objeto de tipo A con la direccion de correo apropiada
		newItem = '<a href="mailto:'+address+'">'+address+'</a>';
		$(prevItem).after(newItem);
	});
}

function fancyBoxes(){
	// Fancybox Cases
	$(".case_imgzoom a").fancybox({
		'padding'			: 0,
		'autoDimensions'	: true,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'fade'
	});
}

function handleSliderChange(e, ui){
	var maxScroll = $(".expanded_container",$(this).parent()).attr("scrollHeight") - $(".expanded_container",$(this).parent()).height();
	$(".expanded_container",$(this).parent()).animate({scrollTop: (100-ui.value) * (maxScroll / 100) }, 1000);
}

function handleSliderSlide(e, ui){
	var maxScroll = $(".expanded_container",$(this).parent()).attr("scrollHeight") - $(".expanded_container",$(this).parent()).height();
	$(".expanded_container",$(this).parent()).attr({scrollTop: (100-ui.value) * (maxScroll / 100) });
}


var case_pos = 1;
var cur_case;

function imgChanger(imgch){
	total = imgch.size();

	imgch.each(function(index){
		if($(this).css('display') != 'none'){
			curimg = $(this);
		}
	});
	if(curimg != false){
		pos = $('img',curimg.parent()).index(curimg);
		next = pos+1;
		if(next == total){
			next = 0;
		}
		curimg.css('display','none');
		$('img', curimg.parent()).eq(next).css('display','block');
	}
}

function fadeImgChanger(imgch,sametime,backwards,type){
	imgch.each(function(index){
		if($(this).css('display') != 'none'){
			curimg = $(this);
		}
	});

	if(curimg != false){
		if(!sametime){
			curimg.fadeOut(350,function(){
				total = imgch.size();
				pos = $(type,$(this).parent()).index($(this));
				next = (!backwards) ? pos+1 : pos-1;
				if(backwards){
					if(next < 0){
						next = (total-1);
					}
				} else {
					if(next == total){
						next = 0;
					}
				}
				$(type, $(this).parent()).eq(next).fadeIn(350);
			});
		} else {
			total = imgch.size();
			pos = $(type,curimg.parent()).index(curimg);
			next = (!backwards) ? pos+1 : pos-1;
			if(backwards){
				if(next < 0){
					next = (total-1);
				}
			} else {
				if(next == total){
					next = 0;
				}
			}
			curimg.fadeOut(1500);
			$(type, curimg.parent()).eq(next).fadeIn(1500);
		}
	}
}
// Scrollbars
function initScrollBar(parentItem){
	scrollbar = $(".expanded_scrollbar",parentItem);
	scrollcontainer = $(".expanded_container",parentItem);

	contheight = scrollcontainer.height();
	txtheight = $(".expanded_content",scrollcontainer).height();
	if(txtheight > contheight){
		scrollbar.css('display','block');
		scrollbar.slider({
			orientation: "vertical",
			animate: true,
			change: handleSliderChange,
			slide: handleSliderSlide,
			value: 100
		});
	} else {
		scrollbar.css('display','none');
	}
}

function openService(thisItem){
	$('.separator_vertical',thisItem.parent()).css('display','none');
	$('.service').each(function(index){
		$(this).css('position','absolute');
		if($('#cases_toggler').css('display') == 'block'){
			if(curtop[index] < 1000){
				$(this).css('top',curtop[index]+580);
			} else {
				$(this).css('top',curtop[index]);
			}
		} else {
			if(curtop[index] > 1000){
				$(this).css('top',curtop[index]-580);
			} else {
				$(this).css('top',curtop[index]);
			}
		}
		$(this).css('left',curleft[index]);
	});
	parentItem = thisItem.parent();
	itempos = $('.service').index(thisItem);
	$('.service').each(function(index){
		if(index != itempos){
			$(this).fadeOut(800);
		}
	});
	if(thisItem.css('left') != curleft[0]){
		thisItem.animate({
			left: curleft[0]
		}, {
			duration: 200*(itempos+1),
			easing: 'easeOutBack',
			complete: function() {
				$('.right',$(this)).fadeIn(600,function(){
					// Hacer elemento estatico
					curexpanded = $(this).parent();
					curexpanded.css('position','static');
					curexpanded.css('top','auto');
					curexpanded.css('left','auto');
				});
				// Scrollbar
				initScrollBar($(this));
			}
		});
	}
}

function closeService(thisItem){
	// Hacer elemento dinamico
	thisItem.css('position','absolute');
	if($('#cases_toggler').css('display') == 'block'){
		if(curtop[0] < 1000){
			thisItem.css('top',curtop[0]+580);
		} else {
			thisItem.css('top',curtop[0]);
		}
	} else {
		if(curtop[0] > 1000){
			thisItem.css('top',curtop[0]-580);
		} else {
			thisItem.css('top',curtop[0]);
		}
	}
	thisItem.css('left',curleft[0]);
	$('.right',thisItem).fadeOut(200,function(){
		parentItem = $(this).parent().parent();
		itempos = $('.service',parentItem).index($(this).parent());
		if($(this).parent().css('left') != curleft[itempos]){
			$(this).parent().animate({
				left: curleft[itempos]
			}, {
				duration: 200*(itempos+1),
				easing: 'easeOutBack',
				complete: function() {
					$('.service').each(function(index){
						if(index != itempos){
							$(this).fadeIn(700);
						}
					});
					$('.separator_vertical',$('#services_list')).fadeIn(700);
					$('.service').each(function(index){
						$(this).css('position','static');
						$(this).css('top','auto');
						$(this).css('left','auto');
					});
				}
			});
		} else {
			$('.service').each(function(index){
				if(index != itempos){
					$(this).fadeIn(800);
				}
			});
			$('.separator_vertical',$('#services_list')).fadeIn(800);
			$('.service').each(function(index){
				$(this).css('position','static');
				$(this).css('top','auto');
				$(this).css('left','auto');
			});
		}
	});
}

function changeThumbCase(curitem,newpos,pos){
	parentItem = curitem.parent().parent();
	imgsParent = curitem.parent();
	$('.switcher_counter', parentItem).text(newpos+' de '+totalimgs);
	$('.img_case', imgsParent).eq(pos).fadeIn('fast');
	tmpname = 'big'+newpos;

	thiscase = parentItem.parent();
	curcase = $('.case_content').index(thiscase);
	newhref = 'images/case'+(curcase+1)+'_'+tmpname+'.jpg';
	$('.case_imgzoom a', parentItem).attr('href',newhref);

	fancyBoxes();
}

var jobitem;
var newImage = new Image();
newImage.src = 'images/jobs_title_long.png';

function enableJobsSelect(){
	$('.jobs_list a').click(function(){
		$('.jobs_list a').each(function(index){
			$(this).unbind('click');
		});
		pos = $('.jobs_list a').index($(this));
		jobitem = $('.jobs_text .job_data').eq(pos);
		// Fade title
		$('.jobs_title').fadeOut(200, function(){
			$('.jobs_title').css('backgroundImage','url("images/jobs_title_long.png")');
			$('.jobs_title .back_btn_jobs').css('display','block');
			$('.jobs_title span').text('Volver');
			$('.jobs_title').fadeIn(200);
		});
		$('.jobs_list').fadeOut(200, function(){
			jobitem.fadeIn(200, function(){
				initScrollBar(jobitem);
				enableJobsBack();
			});
		});

		return false;
	});
}

function enableJobsBack(){
	$('.jobs_title .back_btn_jobs').click(function(){
		$('.jobs_title .back_btn_jobs').unbind('click');
		$('.jobs_text .job_data').each(function(index){
			if($(this).css('display') != 'none'){
				$(this).fadeOut(200);
			}
		});
		$('.jobs_title').fadeOut(200, function(){
			$('.jobs_title').css('backgroundImage','url("images/jobs_title_short.png")');
			$('.jobs_title .back_btn_jobs').css('display','none');
			$('.jobs_title span').text('Estamos buscando:');
			$('.jobs_list').fadeIn(200);
			$('.jobs_title').fadeIn(200, function(){
				enableJobsSelect();
			});
		});
		
		return false;
	});
}

function changeHash(newhash){
	window.location.hash = newhash.replace('sec_','');
}

function openToggler(curItem, parentItem){
	$('h2 .title',curItem).css('fontStyle','italic');
	$('.toggler_img',curItem).attr('src','images/btn-close.png');
	if(parentItem.attr('id') == 'cases_toggler'){
		parentItem.slideDown({
			duration: 900,
			easing: 'easeInOutCubic',
			complete: function(){
				// Scroll To
				scrollTarget = '#'+$(this).parent().attr('id');
				$.scrollTo(scrollTarget, 1000, { onAfter:changeHash(scrollTarget) } );
				// Scrollbar
				initScrollBar($(this));
				$('.case_imgswitcher',$(this)).css('display','block');
			}
		});
	} else {
		parentItem.slideDown({
			duration: 900,
			easing: 'easeInOutCubic',
			complete: function(){
				// Scroll To
				scrollTarget = '#'+$(this).parent().attr('id');
				$.scrollTo(scrollTarget, 1000, { onAfter:changeHash(scrollTarget) } );

				if($(this).attr('id') == 'services_toggler'){
					expanded = false;
					curexpanded = null;
					$('.right',parentItem).each(function(index){
						if($(this).css('display') != 'none'){
							expanded = true;
							curexpanded = $(this).parent();
						}
					});
					$('.service').each(function(index){
						curpos = $(this).position();
						if(curleft.length < (index+1)){
							curtop[index] = curpos.top;
							curleft[index] = curpos.left;
						}
					});
				}
			}
		});
	}
}

function closeToggler(curItem, parentItem){
	$('h2 .title',curItem).css('fontStyle','normal');
	$('.toggler_img',curItem).attr('src','images/btn-open.png');
	if(parentItem.attr('id') == 'cases_toggler'){
		$('.case_imgswitcher',parentItem).css('display','none');
	}
	else if(parentItem.attr('id') == 'services_toggler'){
		expanded = false;
		curexpanded = null;
		$('.right',parentItem).each(function(index){
			if($(this).css('display') != 'none'){
				expanded = true;
				curexpanded = $(this).parent();
			}
		});
		if(expanded){
			curexpanded.css('position','static');
			curexpanded.css('top','auto');
			curexpanded.css('left','auto');
		}
	}
	parentItem.slideUp({
		duration: 1200,
		easing: 'easeOutCubic'
	});
}

$(document).ready(function(){
	$('.toggler').each(function(index){
		$(this).click(function(){
			parentItem = $('.toggler_content',$(this).parent());
			if($('.toggler_img',$(this)).attr('src') == 'images/btn-open.png'){
				openToggler($(this), parentItem);
			} else {
				closeToggler($(this), parentItem);
			}

			return false;
		});
		$(this).mouseenter(function(){
			$(this).animate({opacity: 0.80},{queue:false, duration:200});
		});
		$(this).mouseleave(function(){
			$(this).animate({opacity: 1},{queue:false, duration:200});
		});
	});

	// Click izquierdo Cases
	$('#btn_case_dcha').click(function(){
		// Listado de cases
		totalCases = $('.case_item').size();
		if(case_pos*5 < totalCases){
			if(totalCases < ((case_pos+1)*5)){
				desp = (totalCases-(case_pos*5))*173;
			} else {
				desp = 865;
			}
			$('#case_list').animate({marginLeft: '-='+desp},{duration: 900, easing: 'easeOutBack'});
			case_pos++;
		}
		return false;
	});
	// Click derecho Cases
	$('#btn_case_izq').click(function(){
		if(case_pos > 1){
			cur_left = parseInt($('#case_list').css('marginLeft'));
			if((cur_left + 865) > 0){
				desp = 0;
			} else {
				desp = '+=865';
			}
			$('#case_list').animate({marginLeft: desp},{duration: 1000, easing: 'easeOutBack'});
			case_pos--;
		}
		return false;
	});
	// Click en Case
	$('.case_item a').each(function(index){
		$(this).click(function(){
			cur_case = $('li',$(this).parent().parent()).index($(this).parent());
			$('.case_content').each(function(index){
				if($(this).css('display') != 'none'){
					$(this).fadeOut(350, function(){
						pos = cur_case;
						totalimgs = $('.img_case',$('.case_content:eq('+pos+')')).size();
						if(totalimgs <= 1)						{
							$('div.case_imgswitcher', $('div.case_content:eq('+pos+')') ).hide();
						}
						$('.switcher_counter', $('.case_content:eq('+pos+')')).text('1 de '+totalimgs);
						$('.img_case',$('.case_content:eq('+pos+')')).css('display','none');
						$('.img_case:first',$('.case_content:eq('+pos+')')).css('display','block');
						$('.case_content:eq('+pos+')').fadeIn(250);
					});
				}
			});

			return false;
		});
	});

	// Click en anterior/siguiente para imgs de cases
	$('.case_imgswitcher_btns a').each(function(index){
		$(this).click(function(){
			parentItem = $(this).parents('div').eq(2);

			curimg = false;
			$('.img_case', parentItem).each(function(index){
				if($(this).css('display') != 'none'){
					curimg = $(this);
				}
			});

			if(curimg != false){
				pos = $('.img_case',parentItem).index(curimg);
				totalimgs = $('.img_case',parentItem).size();
				if((pos > 0) && ($(this).attr('class') == 'btn_imgant')){
					curimg.fadeOut('fast',function(){
						totalimgs = $('.img_case',$(this).parent()).size();
						pos = $('.img_case',$(this).parent()).index($(this));
						changeThumbCase($(this),pos,(pos-1));
					});
				} else if($(this).attr('class') == 'btn_imgant'){
					curimg.fadeOut('fast',function(){
						totalimgs = $('.img_case',$(this).parent()).size();
						pos = $('.img_case',$(this).parent()).index($(this));
						changeThumbCase($(this),totalimgs,(totalimgs-1));
					});
				} else if(($(this).attr('class') == 'btn_imgsig') && (pos < (totalimgs-1))) {
					curimg.fadeOut('fast',function(){
						totalimgs = $('.img_case',$(this).parent()).size();
						pos = $('.img_case',$(this).parent()).index($(this));
						changeThumbCase($(this),(pos+2),(pos+1));
					});
				} else if($(this).attr('class') == 'btn_imgsig') {
					curimg.fadeOut('fast',function(){
						totalimgs = $('.img_case',$(this).parent()).size();
						pos = $('.img_case',$(this).parent()).index($(this));
						changeThumbCase($(this),1,0);
					});
				}
			}

			return false;
		});
	});

	// Social
	$('#social_buttons a').each(function(index){
		$(this).mouseenter(function(){
			$('img',$(this)).animate({width:20, height:20},{queue:false, duration:300});
		});
		$(this).mouseleave(function(){
			$('img',$(this)).animate({width:26, height:26},{queue:false, duration:300});
		});
	});

	// Inicializacion imagen del primer case
	$('.img_case:first',$('.case_content:eq(0)')).css('display','block');
	totalimgs = $('.img_case',$('.case_content:eq(0)')).size();
	$('.switcher_counter', $('.case_content:eq(0)')).text('1 de '+totalimgs);

	replaceEmails();
	
	// Parties
	$('.btn_vermas').each(function(index){
		$(this).mouseenter(function(){
			$(this).animate({opacity: 0.70},{queue:false, duration:200});
		});
		$(this).mouseleave(function(){
			$(this).animate({opacity: 1},{queue:false, duration:200});
		});
	});

	// Servicios
	$('.service_expander').click(function(){
		thisItem = $(this).parents().eq(2);
		// NO se ha pulsado ningun servicio
		if($('.right',thisItem).css('display') == 'none'){
			$('img',$(this)).attr('src','images/services_back.png');
			openService(thisItem);
		}
		// Ya esta activo uno de ellos
		else {
			$('img',$(this)).attr('src','images/services_expand.png');
			closeService(thisItem);
		}
		
		return false;
	});

	$('.closer a').click(function(){
		thisItem = $(this).parents().eq(2);
		$('.service_expander img',thisItem).attr('src','images/services_expand.png');
		closeService(thisItem);
		
		return false;
	});

	// Jobs
	enableJobsSelect();
	
	// ---- //
	$('.employee_names .employee_prev').click(function(){
		parentitem = $(this).parent();
		$('.employee_name span',parentitem).each(function(index){
			if($(this).css('display') != 'none'){
				grandparent = $(this).parents().eq(3);
				fadeImgChanger($('.employee_name span',grandparent),false,true,'span');
				fadeImgChanger($('.employee_images img',grandparent),false,true,'img');
				fadeImgChanger($('.employee_datas .employee',grandparent),false,true,'.employee');
			}
		});

		return false;
	});

	$('.employee_names .employee_next').click(function(){
		parentitem = $(this).parent();
		$('.employee_name span',parentitem).each(function(index){
			if($(this).css('display') != 'none'){
				grandparent = $(this).parents().eq(3);
				fadeImgChanger($('.employee_name span',grandparent),false,false,'span');
				fadeImgChanger($('.employee_images img',grandparent),false,false,'img');
				fadeImgChanger($('.employee_datas .employee',grandparent),false,false,'.employee');
			}
		});
		return false;
	});
	// ---- //
	
	// Fancybox de Aviso Legal
	$("#inline").fancybox({
		'padding'			: 0,
		'autoDimensions'	: true,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'fade'
	});
	// Fancyboxes para Cases
	fancyBoxes();

	// Preload
	preloadImgs();
	
	// Employee
	initEmployees();
});

$(window).load(function(){
	$('#preloader').css('display','none');
	$('#all_content').css('display','block');

	// Imagenes cabecera
	totalImgs = $('.img_item').size();
	pos = Math.floor(Math.random()*totalImgs);
	if(pos == totalImgs) pos--;
	$('img',$('#img_changer')).eq(pos).fadeIn(1000,function(){
		setInterval("fadeImgChanger($('#img_changer img'),false,false,'img')", 8000);
	});
	// Imagen Keko
	setInterval("imgChanger($('#contact_title span img'))", 200);
	setInterval("fadeImgChanger($('#logos_container img'),true,false,'img')", 6000);

	url = window.location.href;

	if(url.search('#') != -1){
		targetId = url.substr(url.search('#')).replace('#','#sec_');
		curItem = $('.toggler',targetId);
		parentItem = $('.toggler_content',targetId);
		openToggler(curItem, parentItem);
	}
});

var curtop = new Array;
var curleft = new Array;
var itempos;




