// JavaScript Document

/***
Quick quote 
load functions
***/

// Inserta al document el script de date-picker
var script  = document.createElement('script');
script.type = "text/javascript";
script.src  = 'http://'+window.location.host+'/app/modulos/Core/extras/date-picker/js/datepicker_01.js';
script.setAttribute("charset", "utf-8");
document.getElementsByTagName('head')[0].appendChild(script);

function loadQuickQuote(){
		var url = 'http://'+window.location.host+'/quickquote/new_quick_quote.php';
		new Ajax.Updater('cont_quick_quote',url,{
		onSuccess: function(){			
			initMenu();
			loadDatePicker();			
			
			//Obtiene las imagenes de las categorias
			new Ajax.Request("http://"+window.location.host+'/pages/getSpringPics.php',{
				onComplete: function(r){
					$('cont_imagenes').update(r.responseText);
				}			 
			});
	}				 
	});
}

function quickQuote(page)
{	/*
	var pagina = "http://"+window.location.host+"/quick_quote.php";
	if(page=='calc')
	pagina += '?calc=true';
	if(typeof Window != 'undefined' && !q_ventana)	
	{	
		q_oldTop = getWindowHeight()/2 - 265;
		q_oldLeft = getWindowWidth()/2 - 295;
	   win = new Window({ url: pagina,
	   className: "alphacube_quick", width: 630, height: 620,   
	   closable: false,
	   maximizable: false,
	   minimizable: false,
	   resizable:   false,
	   draggable: false,
	   title:"",
	   top: 190,
	   left: parseInt(q_oldLeft),
	   destroyOnClose: true } ); 	   
	   win.show();	   	  	   	  
	}
	*/
	//Como es la pagina index y ya tiene el quickquote cargado, despliega las categorias
	$('part_material').focus();
	$$('.dropdown')[0].onmouseover();
	
}

function qq_reset(){
	window.location = "http://"+window.location.host+"/";
}

function loadDatePicker(){
	if($('quote_date') && $('estimated_award_date'))
		datePickerController.create();
	else setTimeout(loadDatePicker,500); 
}

Event.observe(window,'load',loadQuickQuote);

//Dropdown menu
/**
 * Container Class (Prototype) for the dropDownMenu
 *
 * @param idOrElement     String|HTMLElement  root Node of the menu (ul)
 * @param name            String              name of the variable that stores the result
 *                                            of this constructor function
 * @param customConfigFunction  Function            optional config function to override the default settings
 *                                            for an example see Menu.prototype.config
 */
var Menu = Class.create();
Menu.prototype = {

	initialize: function(idOrElement, name, customConfigFunction) {

		this.name = name;
		this.type = "menu";
		this.closeDelayTimer = null;
		this.closingMenuItem = null;

		this.config();
		if (typeof customConfigFunction == "function") {
			this.customConfig = customConfigFunction;
			this.customConfig();
		}
		this.rootContainer = new MenuContainer(idOrElement, this);
	},

	config: function() {
	  this.collapseBorders = true;
	  this.quickCollapse = true;
	  this.closeDelayTime = 500;
	}

}

var MenuContainer = Class.create();
MenuContainer.prototype = {
	initialize: function(idOrElement, parent) {
		this.type = "menuContainer";
  		this.menuItems = [];
		this.init(idOrElement, parent);
	},

	init: function(idOrElement, parent) {
	  this.element = $(idOrElement);	  
	  this.parent = parent;
	  this.parentMenu = (this.type == "menuContainer") ? ((parent) ? parent.parent : null) : parent;
	  this.root = parent instanceof Menu ? parent : parent.root;
	  this.id = this.element.id;

	  if (this.type == "menuContainer") {
	  	if (this.element.hasClassName("level1")) this.menuType = "horizontal";
		else if (this.element.hasClassName("level2")) this.menuType = "dropdown";
		else this.menuType = "flyout";

	    if (this.menuType == "flyout" || this.menuType == "dropdown") {
	      this.isOpen = false;
		  Element.setStyle(this.element,{
	      	position: "absolute",
	      	top: "0px",
	      	left: "0px",
	      	visibility: "hidden"});
	    } else {
	      this.isOpen = true;
	    }
	  } else {
	    this.isOpen = this.parentMenu.isOpen;
	  }

	  var childNodes = this.element.childNodes;
	  if (childNodes == null) return;

	  for (var i = 0; i < childNodes.length; i++) {
	    var node = childNodes[i];
	    if (node.nodeType == 1) {
	      if (this.type == "menuContainer") {
	        if (node.tagName.toLowerCase() == "li") {
	          this.menuItems.push(new MenuItem(node, this));
	        }
	      } else {
	        if (node.tagName.toLowerCase() == "ul") {
	          this.subMenu = new MenuContainer(node, this);
	        }
	      }
	    }
	  }
	},

	getBorders: function(element) {
	  var ltrb = ["Left","Top","Right","Bottom"];
	  var result = {};
	  for (var i = 0; i < ltrb.length; ++i) {
	    if (this.element.currentStyle)
	      var value = parseInt(this.element.currentStyle["border"+ltrb[i]+"Width"]);
	    else if (window.getComputedStyle)
	      var value = parseInt(window.getComputedStyle(this.element, "").getPropertyValue("border-"+ltrb[i].toLowerCase()+"-width"));
	    else
	      var value = parseInt(this.element.style["border"+ltrb[i]]);
	    result[ltrb[i].toLowerCase()] = isNaN(value) ? 0 : value;
	  }
	  return result;
	},

	open: function() {
	  if (this.root.closeDelayTimer) window.clearTimeout(this.root.closeDelayTimer);
	  this.parentMenu.closeAll(this);
	  this.isOpen = true;
	  if (this.menuType == "dropdown") {
		Element.setStyle(this.element,{
			left: (Position.positionedOffset(this.parent.element)[0]) + "px",
			top: (Position.positionedOffset(this.parent.element)[1] + Element.getHeight(this.parent.element)) + "px"
		});

	  } else if (this.menuType == "flyout") {
	    var parentMenuBorders = this.parentMenu ? this.parentMenu.getBorders() : new Object();
	    var thisBorders = this.getBorders();
	    if (
	      (Position.positionedOffset(this.parentMenu.element)[0] + this.parentMenu.element.offsetWidth + this.element.offsetWidth + 20) >
	      (window.innerWidth ? window.innerWidth : document.body.offsetWidth)
	    ) {
			Element.setStyle(this.element,{
	      		left: (- this.element.offsetWidth - (this.root.collapseBorders ?  0 : parentMenuBorders["left"])) + "px"
			});
	    } else {
			Element.setStyle(this.element,{
	    		left: (this.parentMenu.element.offsetWidth - parentMenuBorders["left"] - (this.root.collapseBorders ?  Math.min(parentMenuBorders["right"], thisBorders["left"]) : 0)) + "px"
			});
	    }
		Element.setStyle(this.element,{
	    	top: (this.parent.element.offsetTop - parentMenuBorders["top"] - this.menuItems[0].element.offsetTop) + "px"
		});
	  }
	  Element.setStyle(this.element,{visibility: "visible"});
	},

	close: function() {
		Element.setStyle(this.element,{visibility: "hidden"});
		this.isOpen = false;
		this.closeAll();
	},

	closeAll: function(trigger) {
		for (var i = 0; i < this.menuItems.length; ++i) {
			this.menuItems[i].closeItem(trigger);
		}
	}

}


var MenuItem = Class.create();

Object.extend(Object.extend(MenuItem.prototype, MenuContainer.prototype), {
	initialize: function(idOrElement, parent) {
		var menuItem = this;
		this.type = "menuItem";
		this.subMenu;
		this.init(idOrElement, parent);
		if (this.subMenu) {
			this.element.onmouseover = function() {
				menuItem.subMenu.open();
			}
		} else {
		if (this.root.quickCollapse) {
		  this.element.onmouseover = function() {
			menuItem.parentMenu.closeAll();
		  }
		}
		  }
		  var linkTag = this.element.getElementsByTagName("A")[0];
		  if (linkTag) {
		 linkTag.onfocus = this.element.onmouseover;
		 this.link = linkTag;
		 this.text = linkTag.text;
		  }
		  if (this.subMenu) {
		this.element.onmouseout = function() {
		  if (menuItem.root.openDelayTimer) window.clearTimeout(menuItem.root.openDelayTimer);
		  if (menuItem.root.closeDelayTimer) window.clearTimeout(menuItem.root.closeDelayTimer);
		  eval(menuItem.root.name + ".closingMenuItem = menuItem");
		  menuItem.root.closeDelayTimer = window.setTimeout(menuItem.root.name + ".closingMenuItem.subMenu.close()", menuItem.root.closeDelayTime);
		}
		  }
	},

	openItem: function() {
	  this.isOpen = true;
	  if (this.subMenu) { this.subMenu.open(); }
	},

	closeItem: function(trigger) {
	  this.isOpen = false;
	  if (this.subMenu) {
	    if (this.subMenu != trigger) this.subMenu.close();
	  }
	}
});


var menu;


function configMenu() {
  this.closeDelayTime = 300;
}

function initMenu() {	
 if($('menu'))
  menu = new Menu('root', 'menu', configMenu);
 else
 setTimeout(initMenu,500);
}


//Event.observe(window, 'load', initMenu, false);


/******
Spring Categories Pictures

funciones para posicionar, mostrar y ocultar las imagenes de las categorias
en el quickquote
******/

var efecto;
var img_anterior;
function mostrarImagen(elemento,parent)
{
	var id = 'img_'+elemento;
	var imgTop = $('menu').positionedOffset()[1];
	//if(parent) $('cont_imagenes').style.top = ((parent*20) + 30) + 'px';	
	if(parent)
	$('cont_imagenes').style.top = (imgTop+(parent*18) + 30)+'px';
	if($(id))
	{
		var left = $('menu').cumulativeOffset();
		left = left[0];
		$('cont_imagenes').style.left = (left - 300) + 'px';
		
		if(efecto) efecto.cancel();			
		if(img_anterior) 
		{
			$(img_anterior).style.zIndex = 1; //manda la imagen anterior atras
			//$(img_anterior).style.display = 'none'; //y la oculta			
		}
		$(id).style.zIndex = 10;			
		efecto = Effect.Appear('cont_imagenes',{ duration: .5 });
		img_anterior = id;
	}
}

function ocultarImagen(elemento)
{
	var id = 'img_'+elemento.replace(' ','-');
	if($(id))
	{
		if(efecto) efecto.cancel();	
		efecto = Effect.Fade('cont_imagenes',{ duration: .4	});									
	}		
}


/***
	funciones para validaciones del quick quote
	- validar fechas
	- validar datos incompletos	
***/

function validarRFQ()
{ 	
	var flag = 1;
	var categoria = $('categoria').value;
	var material = $('part_material').value;
	//var degree = $('part_material_degree').value;
	var descripcion = $('part_description').value;		
	var cantidad = $('Quantity1').value;
	var quote = $('quote_date').value;
	var award = $('estimated_award_date').value;	
	
	if(!categoria || !material || !descripcion || !cantidad || !quote || !award)
		flag = 0;
	
	if(flag == 0)
		alert(msg_quote_validate_incomplete);//Please complete all the required fields to continue
	
	return flag==1?true:false;
}
	
var mailUnico;
var completado;
var actual = 1;
function validarRegistro(noEmail)
{ 	
	var flag = 1;
	
	var company = $('company').value;
	var nombre = $('first_name').value;
	//var apellido = $('last_name').value;		
	var email = $('email').value;
	var phone = $('phone').value;
	if($('registered').value == 0)
		var password = $('qpassword').value;
	else
		var password = 1;
		
	if(!company || !nombre || !phone || !email || !password)
		flag = 0;
	
	if(flag == 0)
		alert(msg_quote_validate_incomplete);//Please complete all the required fields to continue
	else if(!isValidEmail(email))
	{
		flag = 0;
		alert(msg_quote_invalid_email);//Please use a valid email address
	}
	if(!noEmail)
	checkEmail();
	else
	{
		mailUnico = true;
		completado = true;	
	}
	
	while(!completado)
	{
		setTimeout('',500);	
	}
	
	if(flag==1)
		if(!mailUnico){
			flag = 0;
			alert(msg_quote_email_duplicate);//The email account already exists. Please use a different account.
		}
	
	
	return flag==1?true:false;
}
		

function enviarForm()
{		
		document.getElementById('form1').submit();
}

function continuar()
{
	
	if(validarRFQ())
	{
		if(validarRegistro())
		{	
			reviewRFQ();
			//alert('continua');			
			$('paso1').hide();
			$('paso2').show();
		}
	}		
}


function editar()
{
	//Oculta el paso en el que se encuentre actualmente
	$('paso2').hide();
	$('paso1').show();
}

function reviewRFQ()
{
	$$('.labelreg').each(
		function (elemento){
			var rev = $(elemento.id+'_rev');
			if(rev)
			{
			rev.innerHTML = elemento.value.substr(0,300);
				if(elemento.value.length > 300) rev.innerHTML += '...';
			}
		}
	);
	$('part_description_rev').innerHTML = $('part_description_rev').innerHTML.replace(/\n/g,'<br />');
	
}

function userLogin()
{		
	var params = new Hash();
	params.login = $('l_login').value;	
	params.password = $('l_password').value;
	if(params.login = "" || params.password == "")
	{
		alert(msg_quote_login_incomplete);
		return false;	
	}

	var url =  "http://"+window.location.host+'/login_front.php';
	new Ajax.Request(url,{ method:'post', 
		parameters: "login="+$('l_login').value+"&password="+$('l_password').value,
		onSuccess: function(respuesta){			
			if(respuesta.responseText.match('error'))
				alert(msg_quote_login_incorrect);//Login incorrect. Please try again
			else if(respuesta.responseText.match('blocked'))
				alert(msg_quote_login_blocked);//User account has been blocked. Please contact the site Administrators for more information.
			else if(respuesta.responseText.match('supplier'))
				alert(msg_quote_login_supplier);//You have to login as a Buyer to post a Quick Quote
			else
			{							
				$('login_box').hide();
				//$('are_member').hide();
				$('qpassword').setAttribute('disabled','disabled');
				$('qpassword').hide();
				$('label_qpassword').hide();
				//$('label_qpassword2').hide();
				$('login_td1').update();
				$('login_td2').update();
				editar(); 

				var datos = respuesta.responseText.split('|');
				//Inserta los datos en los campos
				// id | company | fname | lname | email | phone
				$('company').value = datos[1];
				$('first_name').value = datos[2]+' '+datos[3];
				//$('last_name').value = datos[3];
				$('email').value = datos[4];
				$('phone').value = datos[5];	
				
				$('registered').value = datos[0];				
				//$ajaxreplace('loginLoad', 'pages/login/check.php',{ loadTxt:'Logueando...' });
				updateLoginInfo();				
			}
		}			 
		});
	

}

function updateLoginInfo(){
	try{
	$('loginLoad').update();
	var mensajeLoading = "<div class='loading'>"+msg_loading+"...</div>";	
	var url = 'http://'+window.location.host+'/pages/login/check.php?home';
	$ajaxreplace('loginLoad',url,{ loadTxt:mensajeLoading });
	//$('loginLoad').style.height = "";
	}
	catch(e){}
}


function showLoginBox(){
	if(typeof(Effect) != 'undefined')
	{
		new Effect.Appear('login_box',{ duration: .6 });
	}
	else
		$('login_box').show();
}

function hideLoginBox(){
	if(typeof(Effect) != 'undefined')
	{
		new Effect.Fade('login_box',{ duration: .6 });
	}
	else
		$('login_box').hide();
}

function validarQuoteDate()
{
	var quote = $('quote_date');
	var award = $('estimated_award_date');
	//Quote time
	var fecha_quote = quote.value;
	var time_quote = new Date(fecha_quote).getTime();		
		time_quote = parseInt(time_quote/1000); 
	//Award time
	var fecha_award = award.value;
	var time_award = new Date(fecha_award).getTime();		
		time_award = parseInt(time_award/1000); 				
	//Today time
	var today = getTodayTime();

	if(time_quote < today)		
	{ alert(msg_quote_date_past); quote.value = getToday(); return false; }//The quote date cannot be a past day
	if(time_quote > time_award)		
	{ alert(msg_quote_date_after_award); quote.value = award.value; return false; }	//The quote date cannot be after the award date					
		
	return true;
}

function validarAwardDate()
{
	var quote = $('quote_date');
	var award = $('estimated_award_date');
	//Quote time
	var fecha_quote = quote.value;
	var time_quote = new Date(fecha_quote).getTime();		
		time_quote = parseInt(time_quote/1000); 
	//Award time
	var fecha_award = award.value;
	var time_award = new Date(fecha_award).getTime();		
		time_award = parseInt(time_award/1000); 				
	//Today time
	var today = getTodayTime();

	if(time_award < today)		
	{ alert(msg_quote_award_past); award.value = getToday(); return false; }//The award date cannot be a past day
	if(time_quote > time_award)		
	{ alert(msg_quote_award_before_quote); award.value = quote.value; return false; }	//The award by date cannot be prior the quote date					
		
	return true;
}

function getTodayTime()
{
	var todayDate = getToday();
	var today = new Date(todayDate).getTime();
		today = parseInt(today/1000); 
	
	return today;
}


function getToday()
{
	var date = new Date();
	var day = date.getDate();
	var month = date.getMonth() + 1;
	var year = date.getFullYear();
	
	var todayDate = month+"/"+day+"/"+year;
	return todayDate;
}

function checkEmail()
{
	var URL = 'http://'+window.location.host+'/app/template/php/checkCampo.php';
	var _checar = 'email';
	var _valor = $('email').value;
	var _en = 'Client';
	
	var params = $H({ campo: _checar , valor: _valor , tabla: _en,cont_ajax: 0 });
	var ajax = new Ajax.Request(URL,{
	asynchronous: false,
	onSuccess: function(respuesta){
		var unique = [];			
		var ajax = [];
		var registrado = $("registered").value;
		eval(respuesta.responseText);
		//alert(unique[0]);
			var unico = (unique[0] && registrado==0)?false:true;
			mailUnico = unico;
			completado = true;
		},
	method: 'post', 
	parameters: params.toQueryString(), 
	onFailure: function() { completado = true; alert(msg_quote_mail_connection_failure); }//connection failure. Please try again.
	});
	
}


function isValidEmail(mail)
{
	var s=mail;
	var filter=/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	if (s.length == 0 ){
		return false;
	}else if (filter.test(s)){
		return true;
	}else{
		return false
	}
}	

function mostrarProfile()
{
	mostrarInput('delivery_address_1');
	mostrarInput('delivery_city');
	mostrarInput('delivery_zip');
	mostrarInput('delivery_country');
	mostrarInput('delivery_state');
	mostrarInput('delivery_phone');
	mostrarInput('delivery_fax');		
}

function mostrarProfile2()
{
	
	if($('mydirection').checked)
	{
		//Guarda los valores y muestra los del perfil
		datos[0] = $('delivery_address_1').value;
		datos[1] = $('delivery_city').value;
		datos[2] = $('delivery_zip').value;
		datos[3] = $('delivery_country').value;
		datos[4] = $('delivery_state').value;
		datos[5] = $('delivery_phone').value;
		datos[6] = $('delivery_fax').value;
		
		$('delivery_address_1').value = $('profile_delivery_address_1').innerHTML;
		$('delivery_city').value = $('profile_delivery_city').innerHTML;
		$('delivery_zip').value = $('profile_delivery_zip').innerHTML;
		$('delivery_country').value = $('profile_delivery_country').innerHTML;
		//Actualiza la lista de estados
		Sel($('delivery_country'),0,$('form1').state,new Array($('form1').delivery_state)); 
		$('delivery_state').value = $('profile_delivery_state').innerHTML;
		$('delivery_phone').value = $('profile_delivery_phone').innerHTML;
		$('delivery_fax').value = $('profile_delivery_fax').innerHTML;
	}
	else
	{
		$('delivery_address_1').value = datos[0];
		$('delivery_city').value = datos[1];
		$('delivery_zip').value = datos[2];
		$('delivery_country').value = datos[3];
		//Actualiza la lista de estados
		Sel($('delivery_country'),0,$('form1').state,new Array($('form1').delivery_state)); 
		$('delivery_state').value = datos[4];
		$('delivery_phone').value = datos[5];
		$('delivery_fax').value = datos[6];	
	}
	
	
}

function mostrarInput(elemento)
{
	$(elemento).style.display = $(elemento).style.display=='none'?'inline':'none';
	$('profile_'+elemento).style.display = $(elemento).style.display=='none'?'inline':'none';
	//Asigna el atributo de requerido al campo
	var requerido =  $(elemento).style.display=='none'?'':'si';
	$(elemento).setAttribute('requerido',requerido);
	
}

/***
Funciones para seleccionar la categoria
***/
//Cambia la subcategoria
function cambiarSubCat(valor)
{
	if(valor > 0)
	{			
		var url = 'http://'+window.location.host+'/app/admin/modulos/RFQ/front/php/getSubcategories.php?idCat='+valor;
		new Ajax.Request(url,{ onSuccess: function(transport){ $('sub_category').innerHTML = transport.responseText; }});
	}
	else
		$('sub_category').innerHTML = '<option value="">&nbsp;</option>';
}


function seleccionarCategoria(id,nombre)
{
	$('categoria').value = id;
	$('cat_seleccionada').innerHTML = 'Selected: '+nombre;
	$('cat_seleccionada').style.display = 'inline';
	if($('categoria_nombre')) $('categoria_nombre').value = nombre;
		
	menu.rootContainer.closeAll();
}

function seleccionarCategoria2(id,nombre)
{
	$('categoria').value = id;
	$('cat_seleccionada').innerHTML = nombre.substr(0,24);
	if(nombre.length > 24)
	$('cat_seleccionada').innerHTML += '...';
	if($('categoria_nombre')) $('categoria_nombre').value = nombre;
	menu.rootContainer.closeAll();
}

var times_checked = 0;
function checkQuoteStatus(stamp){
	if(!validarRFQ() || !validarRegistro(true)) return false;
	var url = 'http://'+window.location.host+'/quickquote/check_quote_status.php?s='+stamp;
	new Ajax.Request(url,{
		onSuccess: function(r){
			
			if(r.responseText.match('inicio'))
			{
				times_checked += 1;
				if(times_checked < 6)
				{
					setTimeout(function(){
						checkQuoteStatus(stamp);					
					},1000);
				}
				else{
					var html ='<span style="text-align:center;width:300px; display:block; margin: 184px 0 0 48px;">'+msg_quote_finish_error+'</span>';
					$('cont_quick_quote').update(html+'<br /><br /><center><a href="javascript:void(0)" onclick="qq_reset()" class="btn_silver" style="float:none; display:inline">'+msq_fullquote_create_new+'</a></center>');
				}
			}
			else if(r.responseText.match('error'))
				var html ='<span style="text-align:center;width:300px; display:block; margin: 184px 0 0 48px;">'+msg_quote_finish_error+'</span>';
			else if(r.responseText.match('fin'))
				var html ='<span style="text-align:center; width:320px; display:block; margin: 174px 0 0 40px;">'+msg_quote_finish_complete+'</span>';
			else if(r.responseText.match('nuevo'))
				var html ='<span style="text-align:center; width:320px; display:block; margin: 152px 0 0 40px;">'+msg_quote_finish_new+'</span>';
		if(!r.responseText.match('inicio'))
		$('cont_quick_quote').update(html+'<br /><br /><center><a href="javascript:void(0)" onclick="qq_reset()" class="btn_silver" style="float:none; display:inline">'+msq_fullquote_create_new+'</a></center>');
		}				 
	});
	
	return true;
}
