var folder = "www/";

function centerPage(){
	var width = getWindowWidth();
	var pageWidth = 1043;
	var min_padingLeft = 35;
	var os_minleft = 0;
	var margin_right = 0;
	if (navigator.appVersion.indexOf("Win")!=-1){
		os_minleft = 0;
		margin_right = 30;
	}else{
		os_minleft = 25;
		margin_right = 15;
	}
	var margin = [ (width - pageWidth)/2 ] - 31;
//	$('#footer').text("Width: " + width + ", pageWidth: " + pageWidth + ", margin: " + margin  ) ;
	if(width > pageWidth){
		if(margin < 25) margin = 25;
		$('#content_bkg').css('padding-left',margin);
		$('#menu_bkg').css('padding-left',margin);
		$('#menu').css('padding-left',min_padingLeft + margin);
		$('#contenido').css('padding-left',  margin);
		$('#menu_box').css('margin-right',40);
		
	}else{
		$('#content_bkg').css('padding-left',0);
		$('#menu_bkg').css('padding-left',0);
		
		$('#menu').css('padding-left',min_padingLeft);
		$('#contenido').css('padding-left',os_minleft);
		$('#menu_box').css('margin-right',margin_right);
	}
	//alert( $('#contenido').css('padding-left'));
}

function clear_elements(){
	var elements = new Array('centroDistribucion'	,'nombre'	,'apellido'	,'compania'	,'puesto'	,'correo'	,'telefono'	,'celular'	,'nextel'	, 'comentario');
	var values = new Array(0						,''			,''			,''			,''			,''			,''			,''			,''			, '');
	var preferenciaArray = new Array('check-correo','check-telefono','check-celular','check-nextel');
	
	for(i=0; i<elements.length; i++){
		$('#'+elements[i]).val(values[i]);
	}
	for(i=0; i<preferenciaArray.length; i++){
		if($('#'+preferenciaArray[i]).attr('class').indexOf('checkbox_on') != -1 )
			$('#'+preferenciaArray[i]).removeClass('checkbox_on');
	}
}

function get_currentpage(){
	var loc = window.location;
	p = loc.href.substring(loc.href.indexOf(loc.host) + loc.host.length + folder.length );
	page = p.substring(p.indexOf('page=')+5);
	if(page == '')
		page = 'inicio';
	return page;
}

function get_medioContactoPreferente(){
	var preferenciaArray = new Array('check-correo','check-telefono','check-celular','check-nextel');
	var response = '';
	for(i=0; i<preferenciaArray.length; i++){
		if($('#'+preferenciaArray[i]).attr('class').indexOf('checkbox_on') != -1 )
			response += $('#'+preferenciaArray[i]).attr('title') + ',';
	}
	if(response.length > 0) response = response.substring(0, response.length-1);
	return response;
}


function getWindowWidth() {
	var windowWidth = 0;
	if (typeof(window.innerWidth) == 'number') {
		windowWidth = window.innerWidth;
	}
	else {
		if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		}
		else {
			if (document.body && document.body.clientWidth) {
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}
	
function gotoTop(div){
	var productos = "pvc,cpvc,abs,pead";
	var empresa = "antecedentes,filosofia,certificados";
	if(document.documentElement.scrollTop > $('#'+div).offset().top || productos.indexOf(div) != -1 || empresa.indexOf(div) != -1){
		$('html, body').animate({
			scrollTop: $('#'+div).offset().top
		}, 1250);
	}
}

function isFormReady(){
	var lang_index = 0;
	var invalid_factory_msgs = ["*Seleccionar Centro."];
	var invalid_name_msgs = ["*Nombre inválido."];
	var invalid_lastname_msgs = ["*Apellido inválido."];
	var invalid_company_msgs = ["*Compañía inválida."];
	var invalid_job_msgs = ["*Puesto inválido."];
	var invalid_message_msgs = ["*Comentario inválido."];
	
	var invalid_mail_msgs = ["*Correo inválido."];
	var invalid_tel_msgs = ["*Teléfono inválido."];
	var invalid_cel_msgs = ["*Celular inválido."];
	var invalid_nextel_msgs = ["*Nextel inválido."];
	
	var no_contact_msgs = ["*Proporcionar al menos un medio de contacto."];
	var flag = true, flag_medioComunicacion = false;
	var mail_regexp = /^[a-zA-Z0-9_\.-]+@[a-zA-z0-9\.-]+\.[a-zA-Z]{2,4}$/;
	var txt_regexp = /^[a-zA-Z0-9_\.,-\?!\s]{2,100}$/;
	var num_regexp = /^[0-9-*()!\s]{4,100}$/;
	var time = 3500;
	
	
	if($('#centroDistribucion').val()==0){
		$('#td-msg_centroDistribucion').css('display','block');
		$('#msg_centroDistribucion').text(invalid_factory_msgs[lang_index]).show(); 
		//$('#msg_centroDistribucion').fadeOut(time);
		flag=false;
	}else
		$('#msg_centroDistribucion').fadeOut(time);
	if(!txt_regexp.exec($('#nombre').val().trim())){
		$('#td-msg_nombre').css('display','block');
		$('#msg_nombre').text(invalid_name_msgs[lang_index]).show(); 
		//$('#msg_nombre').fadeOut(time);
		flag=false;
	}else
		$('#msg_nombre').fadeOut(time);
	if(!txt_regexp.exec($('#apellido').val().trim())){
		$('#td-msg_apellido').css('display','block');
		$('#msg_apellido').text(invalid_lastname_msgs[lang_index]).show(); 
		//$('#msg_apellido').fadeOut(time);
		flag=false;
	}else
		$('#msg_apellido').fadeOut(time);
	if(!txt_regexp.exec($('#compania').val().trim())){
		$('#td-msg_compania').css('display','block');
		$('#msg_compania').text(invalid_company_msgs[lang_index]).show(); 
		//$('#msg_compania').fadeOut(time);
		flag=false;
	}else
		$('#msg_compania').fadeOut(time);
	if(!txt_regexp.exec($('#puesto').val().trim())){
		$('#td-msg_puesto').css('display','block');
		$('#msg_puesto').text(invalid_job_msgs[lang_index]).show(); 
		//$('#msg_puesto').fadeOut(time);
		flag=false;
	}else
		$('#msg_puesto').fadeOut(time);
	if(!txt_regexp.exec($('#comentario').val().trim()) || !txt_regexp.exec($('#comentario').val()) ){
		$('#td-msg_comentario').css('display','block');
		$('#msg_comentario').text(invalid_message_msgs[lang_index]).show(); 
		//$('#msg_comentario').fadeOut(time);
		flag=false;
	}else
		$('#msg_puesto').fadeOut(time);
	
	if($('#correo').val().length > 0 || $('#check-correo').attr('class').indexOf('checkbox_on') != -1){
		if(!mail_regexp.exec($('#correo').val())){
			$('#td-msg_correo').css('display','block');
			$('#msg_correo').text(invalid_mail_msgs[lang_index]).show(); 
			//$('#msg_correo').fadeOut(time);
			flag=false;
		}else{
			$('#msg_correo').fadeOut(time);
			flag_medioComunicacion = true;
		}
	}
	if($('#telefono').val().length > 0 || $('#check-telefono').attr('class').indexOf('checkbox_on') != -1){
		if(!num_regexp.exec($('#telefono').val())){
			$('#td-msg_telefono').css('display','block');
			$('#msg_telefono').text(invalid_tel_msgs[lang_index]).show(); 
			//$('#msg_telefono').fadeOut(time);
			flag=false;
		}else{
			$('#msg_telefono').fadeOut(time);
			flag_medioComunicacion = true;
		}
	}
	if($('#celular').val().length > 0 || $('#check-celular').attr('class').indexOf('checkbox_on') != -1){
		if(!num_regexp.exec($('#celular').val())){
			$('#td-msg_celular').css('display','block');
			$('#msg_celular').text(invalid_cel_msgs[lang_index]).show(); 
			//$('#msg_celular').fadeOut(time);
			flag=false;
		}else{
			$('#msg_celular').fadeOut(time);
			flag_medioComunicacion = true;
		}
	}
	if($('#nextel').val().length > 0 || $('#check-nextel').attr('class').indexOf('checkbox_on') != -1){
		if(!num_regexp.exec($('#nextel').val())){
			$('#td-msg_nextel').css('display','block');
			$('#msg_nextel').text(invalid_nextel_msgs[lang_index]).show(); 
			//$('#msg_nextel').fadeOut(time);
			flag=false;
		}else{
			$('#msg_nextel').fadeOut(time);
			flag_medioComunicacion = true;
		}
	}
	if(!flag_medioComunicacion){
		$('#msg_medioComunicacion').text(no_contact_msgs[lang_index]).show(); 
		//$('#msg_medioComunicacion').fadeOut(time);
		flag=false;
	}
	if(flag){	
		var centroDistribucion = escape($('#centroDistribucion').val());
		var nombre = escape($('#nombre').val());
		var apellido = escape($('#apellido').val());
		var compania = escape($('#compania').val());
		var puesto = escape($('#puesto').val());
		var correo = escape($('#correo').val());;
		var telefono = escape($('#telefono').val());
		var celular = escape($('#celular').val());
		var nextel = escape($('#nextel').val());
		var comentario = escape($('#comentario').val());
		var preferencia = get_medioContactoPreferente();
		$('#msg_mail').text("Enviando correo...").show();
		$('#msg_mail').load('model/send_mail.php?centroDistribucion='+centroDistribucion
														+'&nombre='+nombre
														+'&apellido='+apellido
														+'&compania='+compania
														+'&puesto='+puesto
														+'&correo='+correo
														+'&telefono='+telefono
														+'&celular='+celular
														+'&nextel='+nextel
														+'&comentario='+comentario
														+'&preferencia='+preferencia
														, function(){
															clear_elements();
														}).show().fadeOut((time*2));
	}else{
		$('#msg_mail').text("Favor de llenar la forma correctamente, Gracias.").show();
	}
}

function isNumberKey(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode
	 if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
    return true;
}

function load_centrosDistribucion(){
	$('#panel_centros-distribucion a').mouseover(function(){
		$('#direccion-'+this.title).addClass('dir_hover');
		return false;
	});
	$('#panel_centros-distribucion a').mouseout(function(){
		$('#direccion-'+this.title).removeClass('dir_hover');
		return false;
	});
	
	$('#panel_centros-distribucion div').mouseover(function(){
		$('#'+this.id).addClass('dir_hover');
		$('#link-'+this.id).addClass('locacionHover');
		$('#link-'+this.id).removeClass('locacion');
		return false;
	});
	
	$('#panel_centros-distribucion div').mouseout(function(){
		$('#'+this.id).removeClass('dir_hover');
		$('#link-'+this.id).addClass('locacion');
		$('#link-'+this.id).removeClass('locacionHover');
		return false;
	});
}

function load_contacto(){
	$('.medio-contacto').click(function(){
		if($(this).attr('class').indexOf('checkbox_on') == -1)
			$(this).addClass('checkbox_on');
		else
			$(this).removeClass('checkbox_on');
		return false;
	});
	
	$('#comentario').click(function(){
		setSelectionRange(document.getElementById('comentario'),-5,-5);
	});
}


function setSelectionRange(input, selectionStart, selectionEnd) {
	if (input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	}
	else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}

function setBackground(page){
	if(page == 'empresa' || page == 'productos'){ 		
//		$('body').animate({ backgroundColor: "#45adb4" });
//		$('#subdiv_inicio').animate({ backgroundColor: "#45adb4" });
		
//		$('body').css('background','#45adb4');
//		$('#subdiv_inicio').css('background','#45adb4');
		//$('#footer').addClass('footer'); 
	}
}

function load_homepage(){
	var page = get_currentpage();
	//load_menu();
	load_page(page);
	turnon(page);
	centerPage();
	setBackground(page)
	$(window).resize(function () {
		centerPage();
	});

	$(window).scroll(function () { 
		if(window.pageXOffset > 0 )
			$('#menu').css('background-color','#FFF');
		else
			$('#menu').css('background-color','');
      
    });

	
}

function load_menu(){
/*	$('#menu a').click(function (){
		update_location($(this).attr('href'));
		return false;
	});*/
}

function load_productos(){
	$('#submenu_productos a').click(function(){
		gotoTop($(this).attr('href'));
		return false;
	});
}

function load_empresa(){
	$('#submenu_productos a').click(function(){
		gotoTop($(this).attr('href'));
		return false;
	});
}

function loading(div){
	$('#'+div).html('<br/><div style=\"margin: 100px;\"><img src=\"media/imagenes/loader.gif\" alt=\"loading\" width=\"50px\" /></div>');	
}

function turnon(page){
	var clase = new Array('inicio','empresa','productos','distribucion','contacto');
	for(i=0; i<clase.length; i++){
		$('#menu-'+clase[i]).removeClass();
	}
	switch(page){
		case 'inicio':
			$('#menu-inicio').addClass("selected");
			$('#menu-empresa').addClass("underselected");
		break;
		case 'empresa':
			$('#menu-inicio').addClass("overselected");
			$('#menu-empresa').addClass("selected");
			$('#menu-productos').addClass("underselected");
		break;
		case 'productos':
			$('#menu-empresa').addClass("overselected");
			$('#menu-productos').addClass("selected");
			$('#menu-distribucion').addClass("underselected");
		break;
		case 'centros-distribucion':
			$('#menu-productos').addClass("overselected");
			$('#menu-distribucion').addClass("selected");
			$('#menu-contacto').addClass("underselected");
		break;
		case 'contacto':
			$('#menu-distribucion').addClass("overselected");
			$('#menu-contacto').addClass("selected");
		break;
	}
}

function load_page(page){
	if(page == 'centros-distribucion')
		load_centrosDistribucion();
	else if(page == 'contacto')
		load_contacto();
	else if(page == 'productos')
		load_productos();
	else if(page == 'empresa')
		load_empresa();
}

function update_info(page){
	var div = 'main-content';
	//$('#mintitmedia').load('model/updatePage.php?page='+page);
	$('#'+div).load('view/'+page+'.php', 
		function(){
			//$('#footer').fadeOut();
			$('#contenido').removeClass().addClass(page);
			if(page == 'inicio' || page == 'contacto' || page == 'centros-distribucion'){ 
				$('body').animate({ backgroundColor: "#008F98"});
				$('#subdiv_inicio').animate({ backgroundColor: "#008F98"});
				$('#footer').addClass('footer_home');
			}
			else{ 
				$('body').animate({ backgroundColor: "#45adb4" });
				$('#subdiv_inicio').animate({ backgroundColor: "#45adb4" });
				$('#footer').addClass('footer'); 
			}
			load_page(page);
			//$('#footer').fadeIn();
			gotoTop('contenido');
		}
	);
			
	
/*	
	$('#'+div).animate({
		opacity: 0.0,	
		}, 
		1000,
		function(){
			$('#'+div).load('view/'+page+'.php', 
				function(){
					//$('#footer').load('model/updatePage.php?page='+page);
					$('#footer').fadeOut();
					$('#contenido').removeClass().addClass(page);
					if(page == 'inicio' || page == 'contacto' || page == 'centros-distribucion'){ 
						$('body').animate({ backgroundColor: "#027f88"});
						$('#subdiv_inicio').animate({ backgroundColor: "#027f88"});
						$('#footer').addClass('footer_home');
					}
					else{ 
						$('body').animate({ backgroundColor: "#45adb4" });
						$('#subdiv_inicio').animate({ backgroundColor: "#45adb4" });
						$('#footer').addClass('footer'); 
					}
					load_page(page);
					$('#footer').fadeIn();
					
					$('#'+div).animate({
						opacity:1
						},
						1000
					);
				}
			)
		}
	);*/
}

function update_location(flag){
	var loc = window.location;
	p = loc.href.substring(loc.href.indexOf(loc.host) + loc.host.length+ folder.length );
	if(p.indexOf('#') < 0 && p != '/' && p != '/#'){
		window.location.replace(loc.protocol + '//' + loc.host + '/'+ folder + '#/' + p.substring(p.indexOf('#/')+2));	
	}else{
		parent.location.hash = '/'+flag;
	}
}

function funcRef(){
	page = get_currentpage();
	update_info(page);
	turnon(page);
	return false;	
}

if(window.addEventListener)
	window.addEventListener("load",load_homepage,false);
else
	window.attachEvent("onload", load_homepage, false);
	
//window.onhashchange = funcRef;

