/* JavaScript Document */

var urlBase = ''
/* General #################### */
function openPopUp(windowUrl, windowName, windowWidth, windowHeight, scrolling, isResizable) {
	if (windowUrl != '' && windowName != '' && windowWidth != '' && windowHeight != '') {
		if (Boolean(scrolling) == true) {
				scrolling = 'yes'
			} else {
				scrolling = 'no'
		}
		if (Boolean(isResizable) == true) {
				isResizable = 'yes'
			} else {
				isResizable = 'no'
		}
		myWindow = window.open(windowUrl, windowName, 'toolbar=no,location=no,status=yes,menubar=no,scrollbars='+scrolling+',resizable='+isResizable+',width='+windowWidth+',height='+windowHeight+',left=55,top=85').focus();
	} else {
		alert('Problemas ao abrir a Pop Up.');
		window.opener.focus();
		self.close();
	}
}

function openNewsletter() {
	openPopUp('/news/newsletter.asp', 'newsletter', '450', '350', false, false)
}

function mOvr(src,clrOver) {
	if (!src.contains(event.fromElement)) {
	src.bgColor = clrOver;
	}
}

function mOut(src,clrIn) {
	if (!src.contains(event.toElement)) {
	src.style.cursor = 'default';
	src.bgColor = clrIn;
	}
}

function closePage(hasOpener) {
	if (hasOpener == true){
		opener.focus();
	}
	self.close();	
}

function printPage(hasOpener, closeSelf) {
	self.print();
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; 
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
  x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' deve conter um endereço de e-mail válido.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' deve conter somente números.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' deve conter números entre '+min+' e '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' é de preenchimento obrigatório.\n'; }
  } if (errors) alert('Erros:\n'+errors);
  document.MM_returnValue = (errors == '');
}


//Arno ####################
function openComparison(familyId) {
	if (familyId != '') {
		window.open('/produtos/productsFunctions.asp?show=comparison&familyId='+familyId+'', 'compare', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=600,height=520').focus();
	} else {
		alert('Código de família inválido.');
		window.opener.focus();
		self.close();
	}
}
	
function openPromotion(promotionId) {
	if (promotionId != '') {
		openPopUp(urlBase+'/news/promotions/Default.asp?promotionId='+promotionId, 'promotion', 700, 450, true, false)
	} else {
		alert('Código de promoção inválido.');
		window.opener.focus();
		self.close();
	}
}
function pop() {
	window.open('/videos/novidades/2007/duppla/', 'Lavadoras', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};

function pop_zelio() {
	window.open('/videos/novidades/2007/zelio/', 'Zelio', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};
function pop_magiclean() {
	window.open('/videos/novidades/2008/magiclean/', 'Magiclean', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};
function pop_lissi() {
	window.open('/videos/novidades/2008/lissima/', 'Lissima', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};

function pop_laveo() {
	window.open('/videos/novidades/2008/laveo2/', 'Laveo', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};
function pop_duppla() {
	window.open('/videos/novidades/2008/duppla/', 'Duppla', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};


function pop_respect() {
	window.open('/videos/novidades/2011/respect/', 'Respect', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};
function pop_cliclav() {
	window.open('/videos/novidades/2011/cliclav/', 'ClicLav', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};
function pop_durillium() {
	window.open('/videos/novidades/2008/durillium/', 'Durillium', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=490,height=350,left=0,top=0')
};


function pop1() {
	window.open('/novidades/2007/elite/', 'hotsite', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=790,height=511,left=0,top=0')
};

/* sourceSite:
2 = Casa Gourmet */

function openProductDemo(flashSource, sourceSite) {
	if (sourceSite == 2) {
		sourcePath = '/produtos/'
	} else {
		sourcePath = '/produtos/'
	}

	if (flashSource != '') {
		window.open(sourcePath+'productsFunctions.asp?show=productDemo&flashSource='+flashSource+'', 'demonstration', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=300,height=200,left=250,top=200').focus();
	} else {
		alert('Endereço de filme inválido.');
		window.opener.focus();
		self.close();
	}
}

function openProductDiscover(imgDescription, imgSource, sourceSite) {
	if (sourceSite == 2) {
		sourcePath = '/produtos/'
	} else {
		sourcePath = '/produtos/'
	}

if (imgDescription != '' & imgSource != '') {
		window.open(sourcePath+'productsFunctions.asp?show=productDiscover&description='+imgDescription+'&imgSource='+imgSource+'', 'discover', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=340,height=400,left=182,top=85').focus();
	} else {
		alert('Descrição e endereço de imagem inválidos.');
		window.opener.focus();
		self.close();
	}
}

function openProductElements(productId, sourceSite) {
	if (sourceSite == 2) {
		sourcePath = '/produtos/'
	} else {
		sourcePath = '/produtos/'
	}

	if (productId != '') {
		window.open(sourcePath+'productsFunctions.asp?show=productElements&productId='+productId+'', 'elements', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=330,height=400,left=305,top=200').focus();
	} else {
		alert('Código de produto inválido.');
		window.opener.focus();
		self.close();
	}
}

function sendProduct(productId, sourceSite) {
	if (sourceSite == 2) {
		sourcePath = '/produtos/'
		windowWidth = 450
		windowHeight = 300
	} else {
		sourcePath = '/produtos/'
		windowWidth = 462
		windowHeight = 233
	}
	
	if (productId != '') {
		window.open(sourcePath+'productsFunctions.asp?show=sendProduct&productId='+productId+'', 'sendproduct', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width='+windowWidth+',height='+windowHeight+',left=250,top=200').focus();
	} else {
		alert('Código de produto inválido.');
		window.opener.focus();
		self.close();
	}
}

function openStylesQuiz(sourceSite) {
	if (sourceSite == 2) {
		sourcePath = '../cgn/stylesQuiz.asp'
		windowWidth = 452
		windowHeight = 496
	} else {
		sourcePath = '../quiz/stylesQuiz.asp'
		windowWidth = 452
		windowHeight = 496
	}
	openPopUp(sourcePath, 'styleQuiz', windowWidth, windowHeight)
}

function openPublicityVideo(videoSource, productName) {
	openPopUp('/home/publicityVideos.asp?videoSource='+videoSource+'&productName='+productName+'', 'publicityVideo', 320, 305)
}

/* Casa Gourmet #################### */
function openCourses(toInscribe, locationId) {
    if (Boolean(toInscribe) == true) {
        openPopUp('../cgm/courses02.asp?inscription=1', 'courses', 720, 400)
    } else {
        openPopUp('../cgm/courses02.asp?inscription=2', 'courses', 720, 400)
    }
}

function openMap(locationId) {
    openPopUp('../cga/showMap.asp?locationId='+locationId+'', 'showMap', 720, 400)
}

function openRecipesBook() {
    openPopUp('../cgm/recipesBook.asp', 'recipesBook', 450, 330)
}

function printRecipe(recipeId, sourceSite) {
	if (sourceSite == 3) {
		sourcePath = '../../cgm/recipes.asp?recipeId='+recipeId+''
		windowWidth = 770
	} else {
		sourcePath = '../cgm/recipes.asp?recipeId='+recipeId+'&action=printRecipe'
		windowWidth = 675
	}
	openPopUp(sourcePath, 'printRecipe', windowWidth, 400, true);
}

function openRecipesSearch() {
	openPopUp('../../cgm/recipesSearch.asp', 'searchRecipes', 770, 440, true, true);
}

function openDocument(URL) {
	openPopUp(URL, 'document', 675, 450, true, true);
}

function addToRecipesBook(recipeId) {
   openPopUp('../cgm/recipesBook.asp?action=addToBook&recipeId='+recipeId+'', 'recipesBook', 450, 330);
}

function sendRecipe(recipeId) {
	if (recipeId != '') {
		window.open('../cgm/recipesFunctions.asp?show=sendRecipe&recipeId='+recipeId+'', 'sendproduct', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=453,height=301').focus();
	} else {
		alert('Código de receita inválido.');
		window.opener.focus();
		self.close();
	}
}

function openContact(contactType) {
    if (contactType == 'pratica') {
        openPopUp('/cga/contact.asp?contactType='+contactType+'', 'contact', 480, 520)
    } else {
        openPopUp('/cga/contact.asp', 'contact', 480, 520)
    } 
}

function openUseTerms() {
    openPopUp('/cga/termos.asp', 'useTerms', 470, 540)
}

function openSocialProject() {
   openPopUp('/institucional/social02.asp', 'socialProject', 615, 375)
}

function openTourInstructions() {
    openPopUp('/cgt/instr.asp', 'tourInstructions', 462, 478)
}

function openKidsPlay() {
    openPopUp('../cga/play01.asp', 'kidsPlay', 760, 520)
}   

/*itens devem ser apagados em breve*/
function back_page()
{
	frmback.submit()
}

function next_page()
{
	frmnext.submit()
}
/*fim*/


/* Casa Gourmet .TV #################### */
function openVideo(videoSource, videoTitle, videoDescription, windowHeight) {
   openPopUp('../cgm/cgartvPopUp.asp?videoSource='+videoSource+'&videoTitle='+videoTitle+'&videoDescription='+videoDescription+'', 'cgartvVideo', 360, windowHeight)
} 

function openRecipe(recipeId) {
    openPopUp('../cgm/cgartvRecipe.asp?recipeId='+recipeId+'', 'cgartvRecipe', 360, 400)
}

/* Formulários de validação */
function validateNumber(fieldName, event) {
    var valor = fieldName.value;
    var tecla = event.which;
    if (tecla == null) {
        tecla = event.keyCode;
	}
    //Somente números!
    if ( tecla < 48 || tecla > 59){
        event.returnValue = false;
		alert("Este campo aceita somente números.")
		fieldName.value = 1
	return false;
    }
    event.returnValue = true;
    return true;
}

function validateText(fieldName, event) {
    var tecla = event.which;
    if (tecla == null) {
        tecla = event.keyCode;
	}
    //Somente números!
    if ( tecla > 32 && tecla < 65){
        event.returnValue = false;
		alert("Este campo não aceita números.")
	return false;
    }
    event.returnValue = true;
    return true;
}

//# e-mail
function checkEmailStrucure(fieldName) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(fieldName)) 
		return (true);
	else 
		return (false);
}


function validateEmail(fieldName) {
	var valor = fieldName.value
	if(valor != "") {
		if (checkEmailStrucure(valor)==false) {
			alert("E-mail inválido. Digite novamente.");
			fieldName.focus();
			return false;
		}
		
		if (valor.indexOf('@', 0) == -1 || valor.indexOf('.', 3) == -1) { 
			alert("Email inválido. Digite novamente.");
			fieldName.focus();
			return false;
		} 
		return false;
	}
}

//# data
function validaData(dateStr) {
	if (dateStr.value != '') {
		var objeto = dateStr
		var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; 
		var matchArray = dateStr.value.match(datePat); 
		if (matchArray == null) {
			alert("Digite um formato correto: DD/MM/AAAA!")
			objeto.focus();
			objeto.value = ""
		return false;
		}
	
		day = matchArray[1];
		month = matchArray[3];
		year = matchArray[4];
		if (month < 1 || month > 12) {
			alert("Meses válidos são de 1 a 12!");
			objeto.focus();
			objeto.value = ""
		return false;
		}
	
		if (day < 1 || day > 31) {
			alert("Dias válidos são de 1 a 31!");
			objeto.focus();
			objeto.value = ""
		return false;
		}
	
		if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			alert("Mês "+month+" não tem 31 dias!")
			objeto.focus();
			objeto.value = ""
		return false;
		}
	
		if (month == 2) { 
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day>29 || (day==29 && !isleap)) {
				alert("Fevereiro de " + year + " não tem " + day + " dias!");
				objeto.focus();
				objeto.value = ""
			return false;
			}
		}
		return true;
	}
}
		
//# cpf
function validaCPF(fieldName) {
cpf = fieldName.value;
erro = new String;
	if (fieldName.value != "") {
		if (cpf.length < 11) erro += "São necessários 11 digitos para verificação do CPF. "; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas números. "; 
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
			erro += "Número de CPF inválido. ";
			//'fieldName.value = ""
			//'fieldName.focus();
		}

var a = [];
var b = new Number;
var c = 11;
	for (i=0; i<11; i++) {
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
		for (y=0; y<10; y++) b += (a[y] * c--); 
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
			erro +="CPF inválido! ";
	}
	if (erro.length > 0){
		fieldName.value = ""
		alert(erro);
		fieldName.focus();
		return false;
	}
	return true;
	}
}

