//On load page, init the timer which check if the there are anchor changes each 300 ms
   
var currentAnchor = null;
var gbIntItemControl = 1;

$().ready(function(){
		
	setInterval("checarAncla()", 300);
	
	//$("#footer").width($(document).width());
	//$("#loading").css("top",$(document).height()/2 - 100);
	$("#loading").css("top",10);
	$("#loading").css("left",$(document).width()/2 - 100);
	
	$("#divPedirInformes").dialog({ disabled:true, modal:true, autoOpen:false, resizable:false, height:290, width:320 });	

	///////////           ALISTAR  LINKS     //////////////////////
	$("div#DivHeader li a").click(function() {
		showLoading();
		getSeccion($(this).attr("href"));
		//por último devolvemos false, y así el link no se ejecutará realmente
		return false;
	});
	
	//getSeccion("modulos.asp?section=home");

});

////////////////////////////        START MANEJO LINKS AND HISTORY     //////////////////////////////
																								   //
var arrPages = new Array(["", "modulos.asp?section=home"],["#home", "modulos.asp?section=home"],
						  ["#planes", "modulos.asp?section=planes"],
						  ["#portafolio", "modulos.asp?section=portafolio"],
						  ["#productos", "modulos.asp?section=productos"],
						  ["#servicios", "modulos.asp?section=servicios"],
						  ["#monitoreo", "modulos.asp?section=monitoreo"],
						  ["#contacto", "modulos.asp?section=contacto"]
);

var arrIdControlsPage = new Array(['home','divBgSlider', 'Slider', 'Btn_Star', 'td_top_body'],
								  ['planes','Div_Contenido_2', 'Div_Contenido_1', 'divPlanes'],
								  ['portafolio','Envoltura','Btn_Star'],
								  ['productos','Div_Contenido_2','divContenedor'],
								  ['servicios','Div_Contenido_2','divContenedor'],
								  ['monitoreo','Div_Contenido_2','divContenedor'],
								  ['contacto','Div_Contenido_2','divContenedor']
								 );

function checarAncla(){
	var sHashGral = document.location.hash;
	var sHashPuro = document.location.hash;
	
	if(sHashPuro.indexOf("&")>=0){
		sHashPuro = sHashPuro.substring(0, sHashPuro.indexOf("&")).toLowerCase();
	}
	//console.log("currentAnchor = " + currentAnchor + "  hashPuro = " + sHashPuro);
	if(currentAnchor != sHashGral){
		//console.log("currentAnchor = " + currentAnchor + "  hashGral = " + sHashGral + "  hashPuro = " + sHashPuro);

		if(sHashGral.indexOf("catalogo")>=0){
			var url = sHashGral.replace("#catalogo", "modulos.asp?section=catalogo");
			getSeccion(url);
		}else{
			for(var i=0; i<arrPages.length; i++){
				var pagAnchor = arrPages[i][0];
				
				if(pagAnchor.toLowerCase() == sHashPuro.toLowerCase()){
					var xSeccion = arrPages[i][1];
					
					//console.log("(checarAncla) xSeccion=" + xSeccion);
					getSeccion(xSeccion);
				}
			} // CIERRA for
		}
	}
}

function getSeccion(strSeccion){
	
	var contenedor = $("#DivCentral");

	showLoading();
						 
	var link = strSeccion;
	
	seccionGlobal = link;

	var splits = link.split('?');
	var sArguments = "";
	var arrArguments = splits[1].split('&');
	var section="";
	var heightNew=0;
	
	for(var n=0; n<arrArguments.length; n++){
		var sItem = arrArguments[n].toString();

		if(n>0){
			sArguments += "&" + sItem;	
		}
		if(sItem.indexOf("section")>=0){ 
			section = sItem.split('=')[1]; 
		}
	}

	currentAnchor = "#" + section + sArguments;
	document.location.hash = section + sArguments;
		
	$.get(link, function(data){
		contenedor.html(data);
		hideLoading();
		
		///////    SHOW CONTROLS ONE BY ONE   ///
		gbIntItemControl = 1;
	
		for(var d=0; d<arrIdControlsPage.length; d++){
			var arrItemElements = arrIdControlsPage[d];
			
			var primerItem = arrItemElements[0];
			
			if(link.indexOf(primerItem)>=0){
				showControlsPage(arrItemElements);
				break;
			}
		}
		/// _________________________________  ////
	
		setMenuSection(section);
			
		if(link.indexOf("home")>=0){
			$('#slider').nivoSlider({ pauseTime: 7000});
			
			$("#sliderNoticias").easySlider({
				auto:true,
				controlsShow:false,
				vertical:false,
				continuous: true,
				pause: 9000,
				speed: 2000
			});																							 
		}
		
		//if(link.indexOf("portafolio")>=0){
			//$('#slider').nivoSlider();
		//}																   
	});
}

function showControlsPage(arrElements){

//	if (gbIntItemControl == 1){
//		console.log("page="+ arrElements[0]);
//	}
	
	//console.log(gbIntItemControl, arrElements[gbIntItemControl]);
	
	$("#" + arrElements[gbIntItemControl]).fadeTo(800, 1, function(){ 
		if(gbIntItemControl<arrElements.length-1){
			gbIntItemControl++; showControlsPage(arrElements); 
		}
	});
}

function setMenuSection(seccion){
	$("#ulMenu a").attr("className","");
	
	$("#a" + seccion).attr("className","MenuSectionAcive");
}

//Function which chek if there are anchor changes, if there are, sends the ajax petition
/*function checkAnchor(){
	var content = $("#DivCentral");
	var divBg = $("#divBg");
	var divfooter = $("#divFooter");
	
	var query;
	//Check if it has changes
	if(currentAnchor != document.location.hash){
		showLoading();
		//content.fadeTo(500,0);
		currentAnchor = document.location.hash;
		
		switch(currentAnchor)
		{
			case '#home':
				document.title = 'Kropsoft : Desarrollo, Consultoria, Disenio, Servicios Profesionales';
				content.css("height", 614);
				divBg.css("height", 860);
				divfooter.css("top",800);
				break;
			case '#portafolioweb':
				document.title = 'Kropsoft : Portafolio Web, Desarrollo de Interfaces, Disenio de Paginas, Desarrollo Multimedia';
				content.css("height", 614);
				divBg.css("height", 860);
				divfooter.css("top",800);
				break;
			case '#productos':
				document.title = 'Kropsoft : Puntos de Venta, Control de Accesos, Venta de Servicios, Software Personalizado';
				content.css("height", 1004);
				divBg.css("height", 1240);
				divfooter.css("top",1190);
								
				break;
			case '#servicios':
				document.title = 'Kropsoft : Desarrollo, Consultoria, Disenio, Servicios Profesionales, Servicios Web, Servicios Desktop';
				content.css("height", 734);
				divBg.css("height", 980);
				divfooter.css("top",920);
				break;
			case '#planesweb':
				document.title = 'Kropsoft : Empresa Joven, Innovadora, Creativa, Responsable';
				content.css("height", 1144);
				divBg.css("height", 1400);
				divfooter.css("top",1340);
				break;
			case '#sistemaMonitoreo':
				//document.title = 'Kropsoft labs, Experimentos, Innovaciones';
				document.title = 'Sistema de Monitoreo que le permitira revisar QUE y QUE NO les interesa a sus visitantes';
				content.css("height", 714);
				divBg.css("height", 960);
				divfooter.css("top",900);
				break;
			case '#contacto':
				document.title = 'Kropsoft : Contacto, Escribenos, Consultanos';
				content.css("height", 624);
				divBg.css("height", 870);
				divfooter.css("top",810);
				break;
			case '#acceso':
				document.title = 'Kropsoft : Empresa Joven, Innovadora, Creativa, Responsable';
				content.css("height", 1074);
				divBg.css("height", 1330);
				divfooter.css("top",1270);
				break;
		}
		//if there is not anchor, the loads the default section
		if(!currentAnchor)
			query = "section=home";
		else
		{
			//Creates the  string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
			var splits = currentAnchor.substring(1).split('&');
			//Get the section
			var section = splits[0];
			delete splits[0];
			//Create the params string
			var params = splits.join('&');
			query = "section=" + section + params;
		}
		//Send the petition
		//$.get("callbacks.asp", query, function(data){ hideLoading();  content.slideUp(); content.html(data); content.slideDown(); } );
		$.get("callbacks.asp", query, function(data){ hideLoading();  content.html(data); content.fadeTo(3000,1);
				switch(currentAnchor)
				{
					case '#home':
						$("#sliderNoticias").easySlider({
							auto:true,
							controlsShow:false,
							vertical:false,
							continuous: true,
							pause: 9000,
							speed: 2000
						});																							 
						break;
					case '#portafolioweb':
						$("#sliderPortafolio").easySlider({
							auto:false,
							continuous: true,
							numeric: true,
							pause: 9000,
							speed: 3000
						});																							 
						break;
					case '#productos':
						//$("#divPedirInformes").dialog({ disabled:true, modal:true, autoOpen:false, resizable:false, height:290, width:320 });	
						break;
					default:
						$("#sliderNoticias").easySlider({
							auto:true,
							controlsShow:false,
							vertical:false,
							continuous: true,
							pause: 9000,
							speed: 2000
						});	
						break;
				}		
			} );

	}
}
*/

function showLoading(){
	$("#loading")
		.css({visibility:"visible"})
		.css({opacity:"1"})
		.css({display:"block"})
	;
}
//hide loading bar
function hideLoading(){
	
	$("#loading").fadeTo(1000, 0);
};

function changeBg0(divString){
	var div =  $("#"+divString);
	var cssBg = div.css("background-color");
	//alert(cssBg);
	
	if(cssBg=="rgb(255, 255, 255)"){
		div.css("background-color","#405CAF");
	}else{
		div.css("background-color","#FFF");
	}
}

function changeBg(divString, strColor, iOpcion){
	var div =  $("#"+divString);
	
	if(iOpcion==2){
		var strImg = "url(images/" + strColor + ")";
		
		div.css("background-image", strImg);
		//div.css("color", '#ff9900');
		//alert(strImg);
	}else{
		div.css("background-color", strColor);
	}
}


function registroSocio(formulario){
	var content = $("#divRegistroSocio");
	
	var miFormulario = document.getElementById(formulario);
	var strQuery = "";
	var strError = "";
	
	for(i=0; i<miFormulario.length; i++){
		//alert(miFormulario[i].name);
		//if(miFormulario[i].validate.value != ""){
			
			switch(miFormulario[i].name){
				case "Login":
					if(miFormulario[i].value.length<6){
						strError += "El campo "+ miFormulario[i].name + " debe tener minimo 6 caracteres. \n"	
					}
					break;
				case "Contrasena":
					if(miFormulario[i].value.length<6){
						strError += "El campo "+ miFormulario[i].name + " debe tener minimo 6 caracteres. \n"	
					}
					break;
				case "Nombre":
					if(miFormulario[i].value.length==0){
						strError += "El campo "+ miFormulario[i].name + " no puede ser nulo. \n"	
					}
					break;
				case "Telefono":
					if(miFormulario[i].value.length==0){
						strError += "El campo "+ miFormulario[i].name + " no puede ser nulo. \n"	
					}
					break;

				case "Email":
					if ((miFormulario[i].value.indexOf(".")<=0) || (miFormulario[i].value.indexOf("@")<=0)){
						strError += "El campo "+ miFormulario[i].name + " debe ser un email valido. \n"	
					}

					break;
				
			}
			
		//}
		strQuery += miFormulario[i].id + "=" + miFormulario[i].value + "&";
	}
	
	//miFormulario.action += strQuery; 
	
	if(strError!=""){
		alert(strError);	
	}else{
		//document.location.href = miFormulario.action;
	
		$.get(miFormulario.action, strQuery, function(data){   content.html(data);  } );

	}
}

function validarForm(formulario, strDiv){
	var content = $("#"+ strDiv);
	
	var miFormulario = document.getElementById(formulario);
	var strQuery = "";
	var strError = "";
	
	for(i=0; i<miFormulario.length; i++){
		//alert(miFormulario[i].name);
		//if(miFormulario[i].validate.value != ""){
			
			switch(miFormulario[i].name){
				case "Login":
					if(miFormulario[i].value.length<6){
						strError += "El campo "+ miFormulario[i].name + " debe tener minimo 6 caracteres. \n"	
					}
					break;
				case "Contrasena":
					if(miFormulario[i].value.length<6){
						strError += "El campo "+ miFormulario[i].name + " debe tener minimo 6 caracteres. \n"	
					}
					break;
				case "Nombre":
					if(miFormulario[i].value.length==0){
						strError += "El campo "+ miFormulario[i].name + " no puede ser nulo. \n"	
					}
					break;
				case "Telefono":
					if(miFormulario[i].value.length==0){
						strError += "El campo "+ miFormulario[i].name + " no puede ser nulo. \n"	
					}
					break;

				case "Email":
					if ((miFormulario[i].value.indexOf(".")<=0) || (miFormulario[i].value.indexOf("@")<=0)){
						strError += "El campo "+ miFormulario[i].name + " debe ser un email valido. \n"	
					}

					break;
				
			}
			
		//}
		strQuery += miFormulario[i].id + "=" + miFormulario[i].value + "&";
	}
	
	//miFormulario.action += strQuery; 
	
	if(strError!=""){
		alert(strError);	
	}else{
		//document.location.href = miFormulario.action;
		//alert(strQuery);
		var query = miFormulario.action + "?" + strQuery;
		
		$.ajax({
		type: "GET",
		url: query,
		dataType: "html",
		error: function(XMLHttpRequest){ alert("Error: " + XMLHttpRequest);},
		success: function(data) 
			{
				if(data=='Acceso Concedido'){	
					document.location.href='admin/inicio.asp';
				}else if(data=='Acceso Concedido Master'){
					document.location.href='admin/master.asp';
				}else{
					if(data != ""){
						alert(data);
						if(data.indexOf("Error")<0){
	//						$("#txtEmailContra").val("");
	//						abrirEnvioContra(false);
						}
					}
				}
			}
		});

//		$.get(miFormulario.action, strQuery, function(data){   
//			if(data=='Acceso Concedido'){	
//				document.location.href='panel.asp';
//			}else if(data=='Acceso Concedido Master'){
//				document.location.href='admin/master.asp';
//			}else{
//				if(data != ""){
//					alert(data);
//					if(data.indexOf("Error")<0){
////						$("#txtEmailContra").val("");
////						abrirEnvioContra(false);
//					}
//				}
//			}
//		});

	}
}


/*ENVIO FORMULARIO CONTACTO*/

function enviarFormCont(){
	
	var remi = $("#inpRem").val();
	var email = $("#inpEmail").val();
	var telefono = $("#inpTelefono").val();
	var asunto = $("#inpAsu").val();
	var msg = $("#inpMensaje").val();	
	
	if(remi!='' && email!='' && telefono!='' && asunto!='' && msg!=''){
		var query = "remitente="+ remi + "&email="+ email + "&telefono="+ telefono + "&asunto="+ asunto + "&mensaje="+ msg;
		//alert(query);
		
		$.get("enviarEmail.asp", query, function(data){
			alert(data);
		}); 
	}else{
		alert("Todos los campos son obligatorios.")	
	}
}

function borrarFormCont(){
	$("#inpRem").attr('value', '');
	$("#inpEmail").attr('value', '');
	$("#inpTelefono").attr('value', '');
	$("#inpAsu").attr('value', '');
	$("#inpMensaje").attr('value', '');
}


/* PRODUCTOS */
function openPedirInformes(producto){
	if(producto!=''){
		$("#txtProPedInf").attr('value', producto);
		$("#divPedirInformes").dialog("open");
	}else{
		$("#divPedirInformes").dialog("close");
	}
}
function enviarPedirInformes(){
	var remi = $("#txtNomPedInf").val();
	var email = $("#txtEmaPedInf").val();
	var product = $("#txtProPedInf").val();
	
	var query = "remitente="+ remi + "&email="+ email + "&producto="+ product;
	//alert(query);
	var randnum = Math.round(Math.random() * 1000);
	
	//Envia la peticion
	query = "enviarEmail.asp?" + query + "&rnd=" + randnum;
	//alert(query);
	$.ajax({
		type: "GET",
		url: query,
		dataType: "html",
		error: function(XMLHttpRequest){ alert("Error: No se pudo enviar el email, favor de intentar nuevamente o enviar email a info@kropsoft.com");},
		success: function(data) 
		{
	
	//$.get("enviarEmail.asp", query, function(data){
			alert(data);
			openPedirInformes('');
		}
	}); 	
}

function jsFnAbrirDialog(valor){
	//alert(valor);
}
