//===========================================================
//================FUNÇÕES DE VALIDAÇÃO=======================
//===========================================================

function validaCep( obj ){ 
   var cep = obj.value; 

// ## Verifica se possui caracter não-numérico ... 
		if( isNaN( cep ) ){   	
			  alert( "O CEP deve conter apenas números!" );    
			      obj.focus();	
				  return false;
		 }else    // ## ..., então, verifica se o usuário digitou os 9 dígitos
		      if( cep.length != 0 && cep.length < 8  ){
				       alert( "O CEP deve ter 8 dígitos" );
					   obj.focus();	
					   return false;
		      }else
				     if( cep.length == 0 ){
				          return false;
			        }
					else
						return true;
}

function ValidaFormLogin(frm){
	if (frm.email.value == ""){
		alert("Por favor preencha o campo E-mail.\n");
		frm.email.focus();
		return false;
	}
	if (!isMail(frm.email)){
		alert("E-mail inválido.\n");
		frm.email.focus();
		return false;
	}
	if (frm.pwd.value == ""){
		alert("Por favor preencha o campo Senha.\n");
		frm.pwd.focus();
		return false;
	}
	return true;
	//frm.submit();
}

function isMail(mailField){
  strMail = mailField.value;
  var re = new RegExp;
  re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  var arr = re.exec(strMail);
  if (arr == null)
    return(false);
  else
    return(true);
}

function validaMsgFaleConosco(frm){
	nome = replaceAll(frm.nome_fale.value," ","");
	email = replaceAll(frm.email_fale.value," ","");
	assunto = replaceAll(frm.assunto_fale.value," ","");
	duvida = replaceAll(frm.duvida_fale.value," ",""); 
	if (nome == "" || email == "" || assunto == "" || duvida == "" ){
		alert("Favor preencher os campos!");
	}else{
		frm.submit();		
	}
}

//===========================================================
//================FUNÇÕES SELECT PHOTO=======================
//===========================================================

var jSetUp;
var result_resolution="";
var result_page="";

function exibe_pop(){
document.getElementById('Layer4').style.display='block';
document.getElementById('msg_carrinho').style.display='block';
}

String.prototype.trim = function() {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function showTabPartner(p){
	var id_tab_ativa = $('tab_ativo_selec').innerHTML;		
	var obj_tab_ativa = $($('tab_ativo_selec').innerHTML);	

	desativaTabSelec(id_tab_ativa,obj_tab_ativa);			
	ativaTabSelec(p);						
	
	switch (p){
		case "U": 	
			openPanel = "-1"; break;
		case "F": 				
			openPanel = "1"; break;
		case "P": 				
			openPanel = "2"; break;
		case "M": 				
			openPanel = "3"; break;
		case "FB": 				
			openPanel = "4"; break;
	}			
	$('iframe_meusAlbuns').src = "iframe_meusAlbuns.asp?openPanel="+openPanel;			
	$('iframe_minhasFotos').src = "iframe_minhasFotos.asp";
}

function desativaTabSelec(id_tab_ativa,obj_tab_ativa){
	var img_flickr;
	var img_picasa;
	var img_mymoto;
	var img_facebook;
	if  ((navigator.userAgent.indexOf("IE 6.0" ) != -1)) {
		img_flickr = "<img src='/selecaoFotos/images/logo_flickr.gif' class='tab_float_left'>";  
		img_picasa = "<img src='/selecaoFotos/images/logo_picasa.gif' class='tab_float_left'>";
		img_mymoto = "<img src='/selecaoFotos/images/logo_mymoto.gif' class='tab_float_left'>";
		img_facebook = "<img src='/selecaoFotos/images/logo_facebook.gif' class='tab_float_left'>";
	}else{
		img_flickr = '<div id="tab_selec_fotos_flickr_big" class="sprites"></div>'; 
		img_picasa = '<div id="tab_selec_fotos_picasa_big" class="sprites"></div>';
		img_mymoto = '<div id="tab_selec_fotos_motorola_big" class="sprites"></div>';
		img_facebook = '<div id="tab_selec_fotos_facebook_big" class="sprites"></div>';
	}				
	var div_upload_tab		= '<a href=javascript:showTabPartner("U"); class="tab_page_selec_fotos" id="tab_page_selec_fotos_upload">Upload</a>';
	var div_flickr_tab		= '<a href=javascript:showTabPartner("F"); class="tab_page_selec_fotos" id="tab_page_selec_fotos_flickr">'+img_flickr+'</a>';
	var div_picasa_tab		= '<a href=javascript:showTabPartner("P"); class="tab_page_selec_fotos" id="tab_page_selec_fotos_picasa">'+img_picasa+'</a>';
	var div_mymoto_tab		= '<a href=javascript:showTabPartner("M"); class="tab_page_selec_fotos" id="tab_page_selec_fotos_motorola">'+img_mymoto+'</a>';
	var div_facebook_tab	= '<a href=javascript:showTabPartner("FB"); class="tab_page_selec_fotos" id="tab_page_selec_fotos_facebook">'+img_facebook+'</a>';	

	switch (id_tab_ativa){
		case "tab_upload_selec": 	
			obj_tab_ativa.innerHTML = div_upload_tab;								
			break;
		case "tab_upload_flickr": 				
			obj_tab_ativa.innerHTML = div_flickr_tab;		
			break;
		case "tab_upload_picasa": 				
			obj_tab_ativa.innerHTML = div_picasa_tab;		
			break;
		case "tab_upload_motorola": 				
			obj_tab_ativa.innerHTML = div_mymoto_tab;		
			break;
		case "tab_upload_facebook": 				
			obj_tab_ativa.innerHTML = div_facebook_tab;		
			break;	
	}						
}

function ativaTabSelec(p){				
	switch (p) {
		case "U": 
			$('tab_page_selec_fotos_upload').style.backgroundColor = '#d1efed';		
			$('tab_ativo_selec').innerHTML = 'tab_upload_selec';				
			break;
		case "F":
			$('tab_page_selec_fotos_flickr').style.backgroundColor = '#d1efed';		
			$('tab_ativo_selec').innerHTML = 'tab_upload_flickr';													
			break;
		case "P":
			$('tab_page_selec_fotos_picasa').style.backgroundColor = '#d1efed';		
			$('tab_ativo_selec').innerHTML = 'tab_upload_picasa';													
			break;
		case "M":
			$('tab_page_selec_fotos_motorola').style.backgroundColor = '#d1efed';		
			$('tab_ativo_selec').innerHTML = 'tab_upload_motorola';													
			break;
		case "FB":
			$('tab_page_selec_fotos_facebook').style.backgroundColor = '#d1efed';		
			$('tab_ativo_selec').innerHTML = 'tab_upload_facebook';													
			break;
	}		
}

function addPhotoToProject( photo_id, objChk, frame ) {
	
	if (frame == "selectFotos")	{
			frame_origem = window.frames['iframe_minhasFotos'].document;
		}else{
			frame_origem = document;
		}
	
	try {
		gridPics					= frame_origem.getElementById('photoGrid');
		//alert(gridPics.getAttribute('projectPhotos'));
		
		if ( (gridPics.getAttribute('projectPhotos') == null) || (gridPics.getAttribute('projectPhotos') == "") ) {
			strPhotos				= photo_id+",";
			gridPics.setAttribute('projectPhotos', strPhotos);
		}else{
			if ( objChk.checked == true ) {
				strPhotos			= gridPics.getAttribute('projectPhotos')+photo_id+",";
				gridPics.setAttribute('projectPhotos', strPhotos);
			} else {
				splitString			= gridPics.getAttribute('projectPhotos').split(",");
				var strPhotosNew	= "";
				
				for ( i = 0; i < splitString.length-1 ; i++ ) {
					if ( photo_id != splitString[i] ) {
						strPhotosNew += splitString[i]+",";
					}
				}

				if ( strPhotosNew == "" ) {
					gridPics.setAttribute('projectPhotos', null);
				} else {
					gridPics.setAttribute('projectPhotos', strPhotosNew);
				}
			}
		}
		
	} catch ( Erro ) {
		alert( "Erro ao adicionar foto ao projeto: "+Erro.message );
	}
	//alert("gridPics: "+gridPics.getAttribute('projectPhotos'));
}

function addOnePhotoToProject( photo_id, objChk ) {
	try {
		gridPics					= $('photoGrid');
		//alert(gridPics.getAttribute('projectPhotos'));
		
		if ( (gridPics.getAttribute('projectPhotos') == null) || (gridPics.getAttribute('projectPhotos') == "") ) {
			strPhotos				= photo_id+",";
			gridPics.setAttribute('projectPhotos', strPhotos);
			addPhotosOnTray('minhasFotos');
			//alert("aki1");
			setTimeout("gridPics.setAttribute('projectPhotos', '')",1000);
		}else{
			oldStrPhotos = gridPics.getAttribute('projectPhotos');
			strPhotos	 = photo_id+",";
			gridPics.setAttribute('projectPhotos', strPhotos);
			//alert("aki2");
			addPhotosOnTray("minhasFotos");
			setTimeout("gridPics.setAttribute('projectPhotos', oldStrPhotos)",1000);
		}
		
	} catch ( Erro ) {
		alert( "Erro ao adicionar foto ao projeto: "+Erro.message );
	}
}

function addAllToCart(obj) {
	var allPhotos;
	var arrImg;
	var qtdImg;
	var album_id;
	var album_type;
	var photo_id;

	try {
		//$("loadThumbs").style.display = "block";
	
		gridPics = window.frames['iframe_minhasFotos'].document.getElementById("photoGrid");
		if (gridPics == null){
			alert("É necessário escolher um álbum para selecionar as fotos desejadas.");
			return;
		}else{
			if (obj.getAttribute('active') == '0'){
				alert("Por favor, aguarde até que todas as fotos do seu álbum sejam carregadas.");
				return;
			}else{
				//adicionar id de todas fotos do álbum
				qtdFotos = window.frames['iframe_minhasFotos'].document.getElementsByTagName("input").length;
				for (i=0;i<qtdFotos ;i++ ){
					objCheck = window.frames['iframe_minhasFotos'].document.getElementsByTagName("input")[i];
					photo_id = objCheck.id.replace("inp_", "");
					objCheck.checked = true;
					addPhotoToProject(photo_id,objCheck,"selectFotos");
				}
				addPhotosOnTray('selectFotos');
			}
		}

	} catch ( Erro ) {
		alert( "Erro ao adicionar foto ao projeto: "+Erro.message );
	}
	//alert("gridPics: "+gridPics.getAttribute('projectPhotos'));
}

function addPhotosOnTray( frame ) {

	var frame_origem;
	var frame_cart;
	var verifPhotoOnCart = "";
	var indexPhoto = 0;
	var style_div = "";
	var arrPhotosOnCart;
	var x, i, aux;
	var newDiv;
	var photoPartenerIdSelected = "";
	var photoSizeSelected = "";
	var photoDateSelected = "";
	var photoHeightSelected = "";
	var photoWidthSelected = "";
	var photoLargeSelected = "";
	var photoNameSelected = "";
	var copyImg;
	var newImg;
	var newSpan;
	var newImgOut;
	var leftImgOut;
	var topImgOut;

	try {
		/*verifica se seleção de fotos está sendo feita apartir do frame do álbum com o buplo clique 
		ou no frame geral no botão adicionar selecionadas*/
		if (frame == "selectFotos")	{
			frame_origem = window.frames['iframe_minhasFotos'].document;
			frame_cart = window.frames['iframe_meuProjeto'].document;
			frame_cart_body = window.frames['iframe_meuProjeto'];
			elementLoadThumb = document;
		}else{
			frame_origem = document;
			frame_cart = parent.frames['iframe_meuProjeto'].document;
			frame_cart_body = parent.frames['iframe_meuProjeto'];
			elementLoadThumb = parent.document;
		}
		
		/*gridPics recebe o elemento html que tem o atributo responsável por guardar as fotos
		a serem selecionadas para impressão*/
		gridPics = frame_origem.getElementById("photoGrid");
		/*se ele não existir é porque nenhum álbum foi selecionado*/
		if (gridPics == null){
			alert("É necessário escolher um álbum para selecionar as fotos desejadas.");
			return;
		}
		
		/*o atributo projectPhotos guarda a string com os ids concatenados das fotos selecionadas*/
		if ( (gridPics.getAttribute('projectPhotos') == null) || (gridPics.getAttribute('projectPhotos') == "") ) {
			alert("Nenhuma foto selecionada");
		} else {
			
			/*aqui estou parseando a string*/
			strPhotosSelected = gridPics.getAttribute('projectPhotos');
			
			//alert(strPhotosSelected);

			/*arrPhotosSelected->array das fotos selecionadas*/
			arrPhotosSelected = strPhotosSelected.split(",");
			
			/*varrendo todas as fotos selecionadas*/
			for(i=0; i<arrPhotosSelected.length-1; i++){

				/*se este elemento for nulo é pq a referida foto ainda não foi selecionada, logo pode ser adicionada*/
				if (frame_cart.getElementById(arrPhotosSelected[i]) == null){
					if (frame_cart.getElementById("inicial").getAttribute("viewInfo") == "1"){
						frame_cart.getElementById("inicial").innerHTML = "";
						frame_cart.getElementById("inicial").setAttribute("viewInfo", "0");
					}
					
					//carrego string com os dados das fotos selecionadas para o carrinho
					photoPartenerIdSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("partner_id");
					switch (photoPartenerIdSelected) {	
						case "0"://porang
							photoNameSelected = "";
							photoSizeSelected = 0;
							photoDateSelected = 0;
							photoHeightSelected = 0;
							photoWidthSelected = 0;
							photoLargeSelected = "";
							break;
						case "1"://flickr
							photoNameSelected = "";
							photoSizeSelected = 0;
							photoDateSelected = 0;
							photoHeightSelected = 0;
							photoWidthSelected = 0;
							photoLargeSelected = "";
							break;
						case "2"://mymoto
							photoNameSelected = "";
							photoSizeSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_size");
							photoDateSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_date");
							photoHeightSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_height");
							photoWidthSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_width");
							photoLargeSelected = "";
							break;
						case "3"://picasa
							photoNameSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("title");
							photoSizeSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_size");
							photoDateSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_date");
							photoHeightSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_height");
							photoWidthSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_width");
							photoLargeSelected = frame_origem.getElementById(arrPhotosSelected[i]).getAttribute("photo_large");
							break;
					}
					
					//acerto o tamanho da div que receberá as novas fotos
					frame_cart.getElementById("inicial").style.width = frame_cart.getElementsByTagName("div").length*140 + 120 + "px";
					
					//docHtml recebe o element div inicial
					docHTML = frame_cart.getElementById("inicial");
					newDiv = frame_cart.createElement('div');
					indexUltimaDiv = frame_cart.getElementsByTagName("img").length/2;
					
					//copio a imagem selecionada para a bandeja
					if (indexUltimaDiv >= 1){
						ultimaDiv = docHTML.getElementsByTagName("div")[indexUltimaDiv-1];
						indexPhoto = parseInt(ultimaDiv.getAttribute("index")) + 1;
						newDiv.setAttribute("id", "div_"+arrPhotosSelected[i]);
						newDiv.setAttribute("align",ultimaDiv.align);
						newDiv.setAttribute("index", indexPhoto);
						style_div = style_div+"position: "+ultimaDiv.style.position+";";
						style_div = style_div+"float: left;";
						style_div = style_div+"width: "+ultimaDiv.style.width+";";
						style_div = style_div+"height: "+ultimaDiv.style.height+";";
						style_div = style_div+'top: '+ultimaDiv.style.top+';';
						setStyle(newDiv, style_div);
					}else{
						indexPhoto = indexPhoto + 1;
						newDiv.setAttribute("id", "div_"+arrPhotosSelected[i]);
						newDiv.setAttribute("align","center");
						newDiv.setAttribute("index", indexPhoto);
						style_div = style_div+"position: relative;";
						style_div = style_div+"float: left;";
						style_div = style_div+"width: 140px;";
						style_div = style_div+"height: 115px;";
						style_div = style_div+'top: 30px;';
						setStyle(newDiv, style_div);
					}

					docHTML.appendChild(newDiv);

					copyImg		= frame_origem.getElementById(arrPhotosSelected[i]);
					newImg		= frame_cart.createElement('img');
					newImg.setAttribute("id", copyImg.id);
					newImg.setAttribute("src", copyImg.src);
					
					newSpan		= frame_cart.createElement('span');
					newSpan.setAttribute("id", "out_"+copyImg.id);
					if(copyImg.width>copyImg.height){
						if (copyImg.width < 100){
							leftImgOut = copyImg.width-54;
							topImgOut = copyImg.height-2;
						}else{
							leftImgOut = copyImg.width-60;
							topImgOut = copyImg.height-2;
						}
					}else{
						if(copyImg.width<copyImg.height){
							if (copyImg.height < 100){
								leftImgOut = copyImg.width-38;
								topImgOut = copyImg.height-2;
							}else{
								leftImgOut = copyImg.width-46;
								topImgOut = copyImg.height-2;
							}
						}else{
							leftImgOut = copyImg.width-48;
							topImgOut = copyImg.height-2;
						}
					}
					setStyle(newSpan, "position:relative;display:none;z-index:200;width:14px;height:14px;top:"+topImgOut+"px;left:"+leftImgOut+"px;");

					newImgOut	= frame_cart.createElement('img');
					newImgOut.setAttribute("src", "images/bt_excluir.jpg");
					setStyle(newImgOut, "cursor:pointer");
					
					newSpan.appendChild(newImgOut);
					newDiv.appendChild(newSpan);
					newDiv.appendChild(newImg);
					if ( ((frame_cart.getElementsByTagName("div").length-1)*120)>700 ){
						frame_cart_body.scrollTo(((frame_cart.getElementsByTagName("div").length-1)*120),0);
					}
					
					//adiciono às fotos da bandeja os eventos jscript
					addEventTray(newImg, newSpan, newDiv, newImgOut);

					//gravo em sessão os dados das fotos selecionadas para a bandeja
					//document.location.href = "/selecaoFotos/actions/savePhotosOnCart.asp?action=addTray&photo_id="+newImg.id+"&photo_src="+newImg.src+"&photo_partner="+photoPartenerIdSelected+"&photo_size="+photoSizeSelected+"&photo_height="+photoHeightSelected+"&photo_width="+photoWidthSelected+"&photo_large="+photoLargeSelected+"&photo_date="+photoDateSelected+"&photo_name="+photoNameSelected;
					SendRequest("/selecaoFotos/actions/savePhotosOnCart.asp?action=addTray&photo_id="+newImg.id+"&photo_src="+newImg.src+"&photo_partner="+photoPartenerIdSelected+"&photo_size="+photoSizeSelected+"&photo_height="+photoHeightSelected+"&photo_width="+photoWidthSelected+"&photo_large="+photoLargeSelected+"&photo_date="+photoDateSelected+"&photo_name="+photoNameSelected);

					//POG: não é o load, é o countFotos
					elementLoadThumb.getElementById("countFotosTray").innerHTML = parseInt(elementLoadThumb.getElementById("countFotosTray").innerHTML) + 1;

					frame_origem.getElementById('inp_'+arrPhotosSelected[i]).checked=false;
					
				}else{
					frame_origem.getElementById('inp_'+arrPhotosSelected[i]).checked=false;
				}			
			}
		}
		//alt fernando
		gridPics.setAttribute('projectPhotos',"");
	} catch ( Erro ) {
		alert( "Erro ao salvar fotos do projeto: "+Erro.message );
	}			
}//end function addPhotosOnTray

function setStyle( object, styleText ) { 
	if( object.style.setAttribute ) { 
		object.style.setAttribute("cssText", styleText ); 
	} else { 
		object.setAttribute("style", styleText ); 
	} 
}

function addEventTray(objNewImg, objNewSpan, objNewDiv, objNewImgOut){
	if(window.addEventListener){
		objNewImg.addEventListener('mouseover',function(){objNewSpan.style.display='block';objNewDiv.style.top='16px';}, true);
		objNewImg.addEventListener('mouseout',function(){objNewSpan.style.display='none';objNewDiv.style.top='30px';}, true);
		objNewImgOut.addEventListener('mouseover',function(){objNewSpan.style.display='block';objNewDiv.style.top='16px';}, true);
		objNewImgOut.addEventListener("mouseout",function(){objNewSpan.style.display='none';objNewDiv.style.top='30px';}, true);
		objNewImgOut.addEventListener("click",function(){delOneTray(objNewDiv, objNewImg.id);}, true);
	}else
	if(window.attachEvent){
		objNewImg.attachEvent("onmouseover",function(){objNewSpan.style.display='block';objNewDiv.style.top='16px';});
		objNewImg.attachEvent("onmouseout",function(){objNewSpan.style.display='none';objNewDiv.style.top='30px';});
		objNewImgOut.attachEvent("onmouseover",function(){objNewSpan.style.display='block';objNewDiv.style.top='16px';});
		objNewImgOut.attachEvent("onmouseout",function(){objNewSpan.style.display='none';objNewDiv.style.top='30px';});
		objNewImgOut.attachEvent("onclick",function(){delOneTray(objNewDiv, objNewImg.id);});
	}
}

function delOneTray(div, photo_id){
	//strPhotoId.split(",");
	var arrPhotosToCart, arrPhotoPartnerId;
	var strPhotosToCart, strPhotoPartnerId;
	var newStrPhotosToCart = "";
	var newStrPhotoPartnerId = "";
	var divInicial;
	var frame_cart;
	
	if ($("inicial") == null){
		divInicial = parent.frames['iframe_meuProjeto'].document.getElementById("inicial");
		frame_cart = parent.frames['iframe_meuProjeto'].document;
	}else{
		divInicial = $("inicial");
		frame_cart = document;
	}
	
	strPhotosToCart = divInicial.getAttribute("photosToCart");
	strPhotoPartnerId = divInicial.getAttribute("photoPartnerId");

	arrPhotosToCart   = strPhotosToCart.split(",");
	arrPhotoPartnerId = strPhotoPartnerId.split(",");
	
	try{
		div.parentNode.removeChild(div);
		SendRequest("/selecaoFotos/actions/savePhotosOnCart.asp?action=removeTray&photo_id="+photo_id);
		parent.document.getElementById("countFotosTray").innerHTML = parseInt(parent.document.getElementById("countFotosTray").innerHTML)-1;
		for (i=arrPhotosToCart.length-2; i>=0; i--){
			if(arrPhotosToCart[i] != photo_id){
				
				newStrPhotosToCart = arrPhotosToCart[i] + "," + newStrPhotosToCart;
				newStrPhotoPartnerId = arrPhotoPartnerId[i] + "," + newStrPhotoPartnerId;
			}
		}
		divInicial.setAttribute("photosToCart", newStrPhotosToCart);
		divInicial.setAttribute("photoPartnerId", newStrPhotoPartnerId);
		if(frame_cart.getElementsByTagName("div").length == 1){
			divInicial.setAttribute("viewInfo", "1");
			divInicial.style.width = "800px";
			divInicial.innerHTML = '<center><font face="Georgia" size="3" color="#c0c0c0"><br/><br/><br/>Selecione um álbum da lista acima à esquerda e depois selecione as fotos desejadas.</font></center>';
		}
	} catch (Erro) {
		alert( "Erro ao remover foto: "+Erro.message );
	}
}

function delAllCart() {

	var frame_cart = window.frames['iframe_meuProjeto'];
	
	try {
		if (frame_cart.document.getElementsByTagName("div").length > 1){
			frame_cart.$("inicial").innerHTML = "";
			frame_cart.$("inicial").style.width = "800px";
			frame_cart.$("inicial").setAttribute("photosToCart", "");
			frame_cart.$("inicial").setAttribute("photoPartnerId", "");
			frame_cart.$("inicial").setAttribute("viewInfo", "1");
			ret = SendRequestResponse("/selecaoFotos/actions/savePhotosOnCart.asp?action=removeAllTray");
			frame_cart.$("inicial").innerHTML = '<center><font face="Georgia" size="3" color="#c0c0c0"><br/><br/><br/>Selecione um álbum da lista acima à esquerda e depois selecione as fotos desejadas.</font></center>';
			moveSroll('esquerda','mover');
			$("countFotosTray").innerHTML = "0";
		}else{
			alert("Você ainda não selecionou nenhuma foto para o seu carrinho.");
		}
	} catch ( Erro ) {
		alert( "Erro ao remover foto: "+Erro.message );
	}
}

function goCart(){
	var countFotosToCart = parseInt($("countFotosTray").innerHTML);
	if ( countFotosToCart > 0 ) {
		fade('FaderInativo',true,10);fade('popFadeGoCart',true,100);
		//$("popFadeGoCartContent").innerHTML = "Importando foto 1 de " + countFotosToCart + "...";
		//document.location.href = "/custom/goCart.asp";
		window.frames['iframe_goCart'].document.location.href = "/custom/goCart.asp";
		//document.location.href = "/custom/goCart.asp";
	}else{
		alert("Você ainda não selecionou nenhuma foto para o seu carrinho.");
	}
}

function showMsgTrans(partner_id){
	switch (partner_id) {	
		case "0"://upload
			_$("Fader").style.display = "block";
			_$("selecaoFotos_popUpload").style.display = "block";
			break;
		case "1"://flickr
			_$("Fader").style.display = "block";
			_$("selecaoFotos_msgBoxFlickr").style.display = "block";
			break;
		case "2"://mymoto
			_$("Fader").style.display = "block";
			_$("selecaoFotos_msgBoxMymoto").style.display = "block";
			break;
		case "3"://picasa
			_$("Fader").style.display = "block";
			_$("selecaoFotos_msgBoxPicasa").style.display = "block";
			break;
	}
}

function showPrivacidade(partner_id, url){
	switch (partner_id) {	
		case "1"://flickr
			_$("selecaoFotos_msgBoxFlickr").style.display = "none";
			_$("selecaoFotos_msgBoxPrivacidade").style.display = "block";
			break;
		case "2"://mymoto
			_$("selecaoFotos_msgBoxMymoto").style.display = "none";
			_$("selecaoFotos_msgBoxPrivacidade").style.display = "block";
			break;
		case "3"://picasa
			_$("selecaoFotos_msgBoxPicasa").style.display = "none";
			_$("selecaoFotos_msgBoxPrivacidade").style.display = "block";
			break;
	}
	if(window.addEventListener){
		_$("imgProsseguirPrivacidade").addEventListener('click',function(){document.location.href = url;}, true);
	}else 
	if(window.attachEvent){
		_$("imgProsseguirPrivacidade").attachEvent("onclick",function(){document.location.href = url;});
	}
}

function showTransUploadPartner(partner_id, url){
	switch (partner_id) {	
		case "1"://flickr
			_$("selecaoFotos_text_header_msgBoxUploadPartner").innerHTML = "Upload no Flickr";
			break;
		case "2"://mymoto
			_$("selecaoFotos_text_header_msgBoxUploadPartner").innerHTML = "Upload no MyMoto";
			break;
		case "3"://picasa
			_$("selecaoFotos_text_header_msgBoxUploadPartner").innerHTML = "Upload no Picasa";
			break;
	}
	
	_$("Fader").style.display = "block";
	_$("selecaoFotos_msgBoxUploadPartner").style.display = "block";
	
	if(window.addEventListener){
		_$("btn_prosseguir_upload_partner").addEventListener('click',function(){parent.location.href = url;}, true);
	}else 
	if(window.attachEvent){
		_$("btn_prosseguir_upload_partner").attachEvent("onclick",function(){parent.location.href = url;});
	}
}

function goPartner(partner_id,url){
	switch (partner_id){
		case "1"://flickr
			document.location.href = url;
			break;
		case "2"://mymoto
			document.location.href = url;
			break;
		case "3"://picasa
			document.location.href = url;
			break;
	}
}


var intervalo;
function moveSroll(direcao, acao){
	if (acao == "mover"){
		if (direcao == "direita"){
			intervalo = window.setInterval("window.frames['iframe_meuProjeto'].scrollBy(10,0)",10);
		}else{
			intervalo = window.setInterval("window.frames['iframe_meuProjeto'].scrollBy(-10,0)",10);
		}
	}else{
		clearTimeout(intervalo);
	}
}


function viewDivSelectFoto(action){
	if (action == "close"){
		_$('layer_selectFoto').style.display='none';
		_$('Fader').style.display='none';
		_$('iframe_selectFotos').contentWindow.document.getElementById("iframe_meusAlbuns").src = "";
		_$('iframe_selectFotos').contentWindow.document.getElementById("iframe_minhasFotos").src = "";
		_$('iframe_selectFotos').contentWindow.document.getElementById("iframe_meuProjeto").src = "";
		_$('iframe_selectFotos').src = "";

		parent.setPagePair(_$('rightPageNumber').value, _$('leftPageNumber').value);

	}else{
		$('iframe_selectFotos').src = "/books/selecaoFotos/selectFotos.asp";
		_$('layer_selectFoto').style.display='block';
		_$('Fader').style.display='block';
	}
	
}

function checkPhoto(photo_id, tipo){
	if ($('inp_'+photo_id).checked == true){
		$('inp_'+photo_id).checked = false;
	}else{
		$('inp_'+photo_id).checked = true;
	}

	if(tipo == "minhasFotos"){
		addPhotoToProject( photo_id, $(photo_id) );
	}else{
		addPhotoToDelCart(photo_id, $(photo_id) );
	}
}


//===========================================================
//=============FUNÇÕES XMLHTTP REQUEST=======================
//===========================================================

var agt = navigator.userAgent.toLowerCase();
var is_ie = (agt.indexOf('msie') != -1);
var is_ie5 = (agt.indexOf('msie 5') != -1);

function CreateXmlHttpReq(handler) {
	var xmlhttp = null;
	if (is_ie) {
		var control = (is_ie5) ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP";

		try {
			xmlhttp = new ActiveXObject(control);
			xmlhttp.onreadystatechange = handler;
		} catch(e) {
			alert("Active Scripting e controles Activex devem estar habilitados");
		}

	} else {
		xmlhttp = new XMLHttpRequest();
		xmlhttp.onload = handler;
		xmlhttp.onerror = handler;
	}
	return xmlhttp;
}

function DummyHandler() { }

function XmlHttpGET(xmlhttp, url) {
	xmlhttp.open('GET', url, true);
	xmlhttp.send(null);
}

function SendRequest(url) {
	var xmlhttp = CreateXmlHttpReq(DummyHandler);
	XmlHttpGET(xmlhttp, url);
}

function XmlHttpResponse(xmlhttp, url) {
	xmlhttp.open('GET', url, false);
	xmlhttp.send(null);
	return xmlhttp.responseText;
}

function SendRequestResponse(url) {
	var xmlhttp = CreateXmlHttpReq(DummyHandler);
	return XmlHttpResponse(xmlhttp, url);
}


//===========================================================
//=================FUNÇÕES UTILITÁRIAS=======================
//===========================================================

function replaceAll(str, de, para){
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

//converte rgb para hxd
function RGBtoHex(strRGB) {
	var vetRGB;
	if(strRGB.indexOf("#") >= 0){
		return strRGB.replace("#","");
	}else{
		strRGB = strRGB.replace("rgb(","");
		strRGB = strRGB.replace(")","");
		vetRGB = new Array();
		vetRGB = strRGB.split(",");
		return toHex(vetRGB[0])+toHex(vetRGB[1])+toHex(vetRGB[2]);	
	}
}
function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}

function verifBrowser(){
	sAgent = navigator.userAgent;
	//alert("sAgent:" + sAgent)

	if  (sAgent.indexOf("IE") > -1) {
		try{
			return "ie";
		} catch(e){
			return "outros";
		}
	} else {
		return "outros";
	}
}

if(self.Node&&self.Node.prototype){
	Node.prototype.removeNode=remove_Node;
	Node.prototype.replaceNode=replace_Node;
	Node.prototype.swapNode=swap_Node;
	Element.prototype.applyElement=apply_Element;
	Element.prototype.contains=_contains;
	Element.prototype.insertAdjacentText=insertAdj_Text;
	Element.prototype.insertAdjacentHTML=insertAdj_HTML;
	Element.prototype.insertAdjacentElement=insertAdj_El;
	Element.prototype.insert__Adj=insert__Adj;
}

function remove_Node(a1){
	var p=this.parentNode;
	if(p&&!a1){
		var df=document.createDocumentFragment();
		for(var a=0;a<this.childNodes.length;a++){
			df.appendChild(this.childNodes[a])
		}
		p.insertBefore(df,this)
	}
	return p?p.removeChild(this):this;
}

function replace_Node(a1){return this.parentNode.replaceChild(a1,this)}

function swap_Node(a1){
	var p=a1.parentNode;
	var s=a1.nextSibling;
	this.parentNode.replaceChild(a1,this);
	p.insertBefore(this,s)
	return this;
}

function apply_Element(a1,a2){
	if(!a1.splitText){
		a1.removeNode();
		if(a2&&a2.toLowerCase()=="inside"){
			for(var a=0;a<this.childNodes.length;a++){
				a1.appendChild(this.childNodes[a])
			}
			this.appendChild(a1)
		}else{
			var p=this.parentNode;
			p.insertBefore(a1,this);
			a1.appendChild(this);
		}
	return a1;
	}
}

function _contains(a1){
	var r=document.createRange();
	r.selectNode(this);
	return r.compareNode(a1)==3;
}

function insertAdj_Text(a1,a2){
	var t=document.createTextNode(a2||"")
	this.insert__Adj(a1,t);
}

function insertAdj_HTML(a1,a2){
	var r=document.createRange();
	r.selectNode(this);
	var t=r.createContextualFragment(a2);
	this.insert__Adj(a1,t);
}

function insertAdj_El(a1,a2){
	this.insert__Adj(a1,a2);
	return a2;
}

function insert__Adj(a1,a2){
	var p=this.parentNode;
	var s=a1.toLowerCase();
	if(s=="beforebegin"){p.insertBefore(a2,this)}
	if(s=="afterend"){p.insertBefore(a2,this.nextSibling)}
	if(s=="afterbegin"){this.insertBefore(a2,this.childNodes[0])}
	if(s=="beforeend"){this.appendChild(a2)}
}

function $(id) { return document.getElementById(id); }
function _$(id) { return parent.document.getElementById(id); }

/*COMEÇO HISTÓRICO PEDIDOS*/
	function OrderDetails(oid) {
		window.open("/order/details.asp?oid="+oid+"&email=false", "_blank", "width=520,height=460,scrollbars=yes");
	}
	function carregabrw() {
		window.open( '', 'SHOPLINE', 'toolbar=yes, menubar=yes, resizable=yes, status=no, scrollbars=yes, width=675, height=485' );
	}
	function ValidaItau(form) {			
		 form.submit();
	}
/*FIM HISTÓRICO PEDIDOS*/

/*INÍCIO ATUALIZA CADASTRO*/
	function key(event) {
		theKey = event.keyCode;
		if((theKey < 48) || (theKey > 57)){
			//event.returnValue = false;
			return false;
		}else{
			return true;	
		}
	}
	
	function isDtValid(dia, mes, ano){
		if (parseInt(dia) > 31){
			return false;
		}
		if (parseInt(mes) > 12){
			return false;
		}
		if ((parseInt(mes) == 2) && (parseInt(dia) > 29)){
			return false;
		}
		if (parseInt(ano) < 1900){
			return false;
		}
		return true;
	}
	
	function telFocus(str){
		if (str.length == 2){
			$("frmCadastro").telefone.focus();
		}
	}
	function dtDiaFocus(str){
		if (str.length == 8){
			$("frmCadastro").dt_dia.focus();
		}
	}
	function dtMesFocus(str){
		if (str.length == 2){
			$("frmCadastro").dt_mes.focus();
		}
	}
	function dtAnoFocus(str){
		if (str.length == 2){
			$("frmCadastro").dt_ano.focus();
		}
	}
	
	function validaFormCadastroIni(frm){
		if (frm.name.value == ""){
			alert("Por favor preencha o campo Nome.\n");
			frm.name.focus();
			return false;
		}
		if (frm.email.value == ""){
			alert("Por favor preencha o campo E-mail.\n");
			frm.email.focus();
			return false;
		}
		if (!isMail(frm.email)){
			alert("E-mail inválido.\n");
			frm.email.focus();
			return false;
		}
		if (frm.cep.value == ""){
			alert("Por favor preencha o campo CEP.\n");
			frm.cep.focus();
			return false;
		}
		if (frm.cep.value.length < 8) {
			alert("CEP inválido.\n");
			frm.cep.focus();
			return false;
		}

		if (!validaCep(frm.cep)){				
			return false;
		}
		if (frm.pwd.value == ""){
			alert("Por favor preencha o campo Senha.\n");
			frm.pwd.focus();
			return false;
		}
		if (frm.pwd.value.length < 6) {
			alert("Use uma senha com pelo menos 6 caracteres.\n");
			frm.pwd.value = "";
			frm.pwd.focus();
			return false;
		}
		if (frm.conf_pwd.value == ""){
			alert("Você precisa confirmar sua senha.\n");
			frm.conf_pwd.focus();
			return false;
		}
		if (frm.pwd.value != frm.conf_pwd.value){
			alert("Confirmação de senha inválida.\n");
			frm.pwd.value = "";
			frm.conf_pwd.value = "";
			frm.pwd.focus();
			return false;
		}
		
		frm.submit();
	}
	
	function validaFormCadastroNew(frm){
		if (frm.nome.value == ""){
			alert("Por favor preencha o campo Nome.\n");
			frm.name.focus();
			return false;
		}
		if (frm.email.value == ""){
			alert("Por favor preencha o campo E-mail.\n");
			frm.email.focus();
			return false;
		}
		if (!isMail(frm.email)){
			alert("E-mail inválido.\n");
			frm.email.focus();
			return false;
		}

		if (frm.pwd.value == ""){
			alert("Por favor preencha o campo Senha.\n");
			frm.pwd.focus();
			return false;
		}
		if (frm.pwd.value.length < 6) {
			alert("Use uma senha com pelo menos 6 caracteres.\n");
			frm.pwd.value = "";
			frm.pwd.focus();
			return false;
		}
		if (frm.conf_pwd.value == ""){
			alert("Você precisa confirmar sua senha.\n");
			frm.conf_pwd.focus();
			return false;
		}
		if (frm.pwd.value != frm.conf_pwd.value){
			alert("Confirmação de senha inválida.\n");
			frm.pwd.value = "";
			frm.conf_pwd.value = "";
			frm.pwd.focus();
			return false;
		}
		
		if (frm.ddd.value == ""){
			alert("Por favor preencha o campo DDD.\n");
			frm.ddd.focus();
			return false;
		}
		if (frm.telefone.value == ""){
			alert("Por favor preencha o campo Telefone.\n");
			frm.telefone.focus();
			return false;
		}
		if (frm.telefone.value.length < 8) {
			alert("Telefone inválido.\n");
			frm.telefone.value = "";
			frm.telefone.focus();
			return false;
		}
		if (frm.dt_dia.value == ""){
			alert("Por favor preencha o campo Dia da Data de Nascimento.\n");
			frm.dt_dia.focus();
			return false;
		}
		if (frm.dt_mes.value == ""){
			alert("Por favor preencha o campo Mes da Data de Nascimento.\n");
			frm.dt_mes.focus();
			return false;
		}
		if (frm.dt_ano.value == ""){
			alert("Por favor preencha o campo Ano da Data de Nascimento.\n");
			frm.dt_ano.focus();
			return false;
		}
		if (!isDtValid(frm.dt_dia.value, frm.dt_mes.value, frm.dt_ano.value)){
			alert("Data inválida.\n");
			frm.dt_dia.value = "";
			frm.dt_mes.value = "";
			frm.dt_ano.value = "";
			frm.dt_dia.focus();
			return false;
		}
		var btn = valButton(frm.sexo);
		if (btn == null){ 
			alert('Por favor preencha o campo Sexo.\n');
			return false;
		}
	
		if(!frm.check_aceito.checked)	{
			alert("Você deve concordar com os termos de uso para completar a operação.\n");
			return false;
		}
	
		// Teste do captcha
		try{
	
			if (frm.CaptchaStr.value==""){
				alert('Digite o código de verificação.\n' );
				frm.CaptchaStr.focus();
				return false;
			}
	
			var captcha_ok; // verifico se os destinatarios encontram-se na base
			navegador_usuario = navigator.userAgent.toUpperCase();				
			if (navegador_usuario.indexOf("FIREFOX") == -1){ //BUG FIREFOX
				captcha_ok = getRequestSync("/acesso/captcha/valida.asp?valor=" + frm.CaptchaStr.value );
				if (captcha_ok != "1") {
					alert('Código de verificação incorreto. Por favor digite-o novamente.\n');
					captchaImg.innerHTML = ""
					captchaImg.innerHTML = "<img src='/acesso/captcha/CAPTCHA.asp?CaptchaType=2' height='55' width='200'>"
					return false;
				}
			}
		}catch(e){
			alert('Erro captcha:' + e.description )
			return false;
		}  
		
		frm.submit();
	}
	
	function ValidaFormForgot(frm){
		if (frm.email.value == ""){
			alert("Por favor preencha o campo E-mail.\n");
			frm.email.focus();
			return false;
		}
		if (!isMail(frm.email)){
			alert("E-mail inválido.\n");
			frm.email.focus();
			return false;
		}
		frm.submit();
	}
	
	function ValidaFormLogin(frm){
		if (frm.email.value == ""){
			alert("Por favor preencha o campo E-mail.\n");
			frm.email.focus();
			return false;
		}
		if (!isMail(frm.email)){
			alert("E-mail inválido.\n");
			frm.email.focus();
			return false;
		}
		if (frm.pwd.value == ""){
			alert("Por favor preencha o campo Senha.\n");
			frm.pwd.focus();
			return false;
		}
		
		frm.submit();
	}
	
	function ValidaFormLoginAltFkr(frm){
		if (frm.email_out.value == ""){
			alert("Por favor preencha o campo E-mail.\n");
			frm.email_out.focus();
			return false;
		}
		if (!isMail(frm.email_out)){
			alert("E-mail inválido.\n");
			frm.email_out.focus();
			return false;
		}
		if (frm.pwd_out.value == ""){
			alert("Por favor preencha o campo Senha.\n");
			frm.pwd_out.focus();
			return false;
		}
		
		frm.submit();
	}
	// INICIO FERNANDO
	function ValidaFormAtualizaCadastro(frm) {
		if (frm.name.value == ""){
			alert("Por favor preencha o campo Nome.\n");
			frm.name.focus();
			return false;
		}
		if (frm.email.value == ""){
			alert("Por favor preencha o campo E-mail.\n");
			frm.email.focus();
			return false;
		}
		if (!isMail(frm.email)){
			alert("E-mail inválido.\n");
			frm.email.focus();
			return false;
		}
		if (frm.cep.value == ""){
			alert("Por favor preencha o campo CEP.\n");
			frm.cep.focus();
			return false;
		}
		if (frm.cep.value.length < 8) {
			alert("CEP inválido.\n");
			frm.cep.focus();
			return false;
		}
		if (!validaCep(frm.cep)){				
			return false;
		}
		if (frm.pwd.value != ""){
			if (frm.pwd.value.length < 6) {
				alert("Use uma senha com pelo menos 6 caracteres.\n");
				frm.pwd.value = "";
				frm.pwd.focus();
				return false;
			}
			if (frm.conf_pwd.value == "" ){
				alert("Você precisa confirmar sua senha.\n");
				frm.conf_pwd.focus();
				return false;
			}	
			if (frm.pwd.value != frm.conf_pwd.value){
				alert("Confirmação de senha inválida.\n");
				frm.pwd.value = "";
				frm.conf_pwd.value = "";
				frm.pwd.focus();
				return false;
			}
		}
	
		if (frm.endereco.value == ""){
			alert("Por favor preencha o campo Endereço.\n");
			frm.endereco.focus();
			return false;
		}
		if (frm.numero.value == ""){
			alert("Por favor preencha o campo Número.\n");
			frm.numero.focus();
			return false;
		}
		if (frm.bairro.value == ""){
			alert("Por favor preencha o campo Bairro.\n");
			frm.bairro.focus();
			return false;
		}
		if (frm.estado.value == "-99"){
			alert("Por favor preencha o campo Estado.\n");
			frm.estado.focus();
			return false;
		}
		if (frm.ddd.value == ""){
			alert("Por favor preencha o campo DDD.\n");
			frm.ddd.focus();
			return false;
		}
		if (frm.telefone.value == ""){
			alert("Por favor preencha o campo Telefone.\n");
			frm.telefone.focus();
			return false;
		}
		if (frm.telefone.value.length < 8) {
			alert("Telefone inválido.\n");
			frm.telefone.value = "";
			frm.telefone.focus();
			return false;
		}
		if (frm.dt_dia.value == ""){
			alert("Por favor preencha o campo Dia da Data de Nascimento.\n");
			frm.dt_dia.focus();
			return false;
		}
		if (frm.dt_mes.value == ""){
			alert("Por favor preencha o campo Mes da Data de Nascimento.\n");
			frm.dt_mes.focus();
			return false;
		}
		if (frm.dt_ano.value == ""){
			alert("Por favor preencha o campo Ano da Data de Nascimento.\n");
			frm.dt_ano.focus();
			return false;
		}
		if (!isDtValid(frm.dt_dia.value, frm.dt_mes.value, frm.dt_ano.value)){
			alert("Data inválida.\n");
			frm.dt_dia.value = "";
			frm.dt_mes.value = "";
			frm.dt_ano.value = "";
			frm.dt_dia.focus();
			return false;
		}
		
		if (frm.password_old.value == ""){
			alert("Por favor preencha a sua senha atual.\n");
			frm.password_old.focus();
			return false;
		}
		
		var result
	
		result = SendRequestResponse("validaSenha.asp?password="+frm.password_old.value);
		
		//alert("result = "+result);
		
		if (result == "false"){		
			alert("Senha inválida!");
			frm.password_old.value = "";
			frm.password_old.focus();
			return false;
		}else{
			//alert("senha valida!");
			$("loadWriting").style.display = "block";
			frm.submit(); 	
		}
	}
	
	function CarregaDetalhes(imagem,regiao) {		
		if (validaCep($('cep')) ){
			regiao.style.display='inline';
			document.frmProcessa.zip_code.value = document.frmCadastro.cep.value; 
			document.frmProcessa.submit();						
		}else{
			document.getElementById('cep').value = "";
		}		
	}
	//FIM FERNANDO
	
	function ValidaFormCadastro(frm) {
		if (frm.endereco.value == ""){
			alert("Por favor preencha o campo Endereço.\n");
			frm.endereco.focus();
			return false;
		}
		if (frm.numero.value == ""){
			alert("Por favor preencha o campo Número.\n");
			frm.numero.focus();
			return false;
		}
		if (frm.bairro.value == ""){
			alert("Por favor preencha o campo Bairro.\n");
			frm.bairro.focus();
			return false;
		}
		if (frm.estado.value == "-99"){
			alert("Por favor preencha o campo Estado.\n");
			frm.estado.focus();
			return false;
		}
		if (frm.ddd.value == ""){
			alert("Por favor preencha o campo DDD.\n");
			frm.ddd.focus();
			return false;
		}
		if (frm.telefone.value == ""){
			alert("Por favor preencha o campo Telefone.\n");
			frm.telefone.focus();
			return false;
		}
		if (frm.telefone.value.length < 8) {
			alert("Telefone inválido.\n");
			frm.telefone.value = "";
			frm.telefone.focus();
			return false;
		}
		if (frm.dt_dia.value == ""){
			alert("Por favor preencha o campo Dia da Data de Nascimento.\n");
			frm.dt_dia.focus();
			return false;
		}
		if (frm.dt_mes.value == ""){
			alert("Por favor preencha o campo Mes da Data de Nascimento.\n");
			frm.dt_mes.focus();
			return false;
		}
		if (frm.dt_ano.value == ""){
			alert("Por favor preencha o campo Ano da Data de Nascimento.\n");
			frm.dt_ano.focus();
			return false;
		}
		if (!isDtValid(frm.dt_dia.value, frm.dt_mes.value, frm.dt_ano.value)){
			alert("Data inválida.\n");
			frm.dt_dia.value = "";
			frm.dt_mes.value = "";
			frm.dt_ano.value = "";
			frm.dt_dia.focus();
			return false;
		}
		var btn = valButton(frm.sexo);
		if (btn == null){ 
			alert('Por favor preencha o campo Sexo.\n');
			return false;
		}
	
		if(!frm.check_aceito.checked)	{
			alert("Você deve concordar com os termos de uso para completar a operação.\n");
			return false;
		}
	
		// Teste do captcha
		try{
	
			if (frm.CaptchaStr.value==""){
				alert('Digite o código de verificação.\n' );
				return false;
			}
	
			var captcha_ok; // verifico se os destinatarios encontram-se na base
			navegador_usuario = navigator.userAgent.toUpperCase();				
			if (navegador_usuario.indexOf("FIREFOX") == -1){ //BUG FIREFOX
				captcha_ok = getRequestSync("/acesso/captcha/valida.asp?valor=" + frm.CaptchaStr.value );
				if (captcha_ok != "1") {
					alert('Código de verificação incorreto. Por favor digite-o novamente.\n');
					captchaImg.innerHTML = ""
					captchaImg.innerHTML = "<img src='/acesso/captcha/CAPTCHA.asp?CaptchaType=2' height='55' width='200'>"
					return false;
				}
			}
		}catch(e){
			alert('Erro captcha:' + e.description )
			return false;
		}  
		
		$("loadWriting").style.display = "block";
		frm.submit(); 	
	}
	
	function ValidaFormCadastroPartner(frm) {
		if (frm.nome.value == ""){
			alert("Por favor preencha o campo Nome.\n");
			frm.name.focus();
			return false;
		}
		if (frm.email.value == ""){
			alert("Por favor preencha o campo E-mail.\n");
			frm.email.focus();
			return false;
		}
		if (!isMail(frm.email)){
			alert("E-mail inválido.\n");
			frm.email.focus();
			return false;
		}
		if (frm.cep.value == ""){
			alert("Por favor preencha o campo CEP.\n");
			frm.cep.focus();
			return false;
		}
		if (frm.cep.value.length < 8) {
			alert("CEP inválido.\n");
			frm.cep.focus();
			return false;
		}
		if (frm.pwd.value != ""){
			if (frm.pwd.value.length < 6) {
				alert("Use uma senha com pelo menos 6 caracteres.\n");
				frm.pwd.value = "";
				frm.pwd.focus();
				return false;
			}
			if (frm.conf_pwd.value == "" ){
				alert("Você precisa confirmar sua senha.\n");
				frm.conf_pwd.focus();
				return false;
			}	
			if (frm.pwd.value != frm.conf_pwd.value){
				alert("Confirmação de senha inválida.\n");
				frm.pwd.value = "";
				frm.conf_pwd.value = "";
				frm.pwd.focus();
				return false;
			}
		}
		if (frm.endereco.value == ""){
			alert("Por favor preencha o campo Endereço.\n");
			frm.endereco.focus();
			return false;
		}
		if (frm.numero.value == ""){
			alert("Por favor preencha o campo Número.\n");
			frm.numero.focus();
			return false;
		}
		if (frm.bairro.value == ""){
			alert("Por favor preencha o campo Bairro.\n");
			frm.bairro.focus();
			return false;
		}
		if (frm.estado.value == "-99"){
			alert("Por favor preencha o campo Estado.\n");
			frm.estado.focus();
			return false;
		}
		if (frm.ddd.value == ""){
			alert("Por favor preencha o campo DDD.\n");
			frm.ddd.focus();
			return false;
		}
		if (frm.telefone.value == ""){
			alert("Por favor preencha o campo Telefone.\n");
			frm.telefone.focus();
			return false;
		}
		if (frm.telefone.value.length < 8) {
			alert("Telefone inválido.\n");
			frm.telefone.value = "";
			frm.telefone.focus();
			return false;
		}
		if (frm.dt_dia.value == ""){
			alert("Por favor preencha o campo Dia da Data de Nascimento.\n");
			frm.dt_dia.focus();
			return false;
		}
		if (frm.dt_mes.value == ""){
			alert("Por favor preencha o campo Mes da Data de Nascimento.\n");
			frm.dt_mes.focus();
			return false;
		}
		if (frm.dt_ano.value == ""){
			alert("Por favor preencha o campo Ano da Data de Nascimento.\n");
			frm.dt_ano.focus();
			return false;
		}
		if (!isDtValid(frm.dt_dia.value, frm.dt_mes.value, frm.dt_ano.value)){
			alert("Data inválida.\n");
			frm.dt_dia.value = "";
			frm.dt_mes.value = "";
			frm.dt_ano.value = "";
			frm.dt_dia.focus();
			return false;
		}
		var btn = valButton(frm.sexo);
		if (btn == null){ 
			alert('Por favor preencha o campo Sexo.\n');
			return false;
		}
	
		if(!frm.check_aceito.checked)	{
			alert("Você deve concordar com os termos de uso para completar a operação.\n");
			return false;
		}
	
		// Teste do captcha
		try{
	
			if (frm.CaptchaStr.value==""){
				alert('Digite o código de verificação.\n' );
				return false;
			}
	
			var captcha_ok; // verifico se os destinatarios encontram-se na base
			navegador_usuario = navigator.userAgent.toUpperCase();				
			if (navegador_usuario.indexOf("FIREFOX") == -1){ //BUG FIREFOX
				captcha_ok = getRequestSync("/acesso/captcha/valida.asp?valor=" + frm.CaptchaStr.value );
				if (captcha_ok != "1") {
					alert('Código de verificação incorreto. Por favor digite-o novamente.\n');
					captchaImg.innerHTML = ""
					captchaImg.innerHTML = "<img src='/acesso/captcha/CAPTCHA.asp?CaptchaType=2' height='55' width='200'>"
					return false;
				}
			}
		}catch(e){
			alert('Erro captcha:' + e.description )
			return false;
		}  
		
		$("loadWriting").style.display = "block";
		frm.submit(); 	
	}
	
	
	function valButton(btn) {
		var cnt = -1;
		for (var i=btn.length-1; i > -1; i--) {
			if (btn[i].checked) {cnt = i; i = -1;}
		}
		if (cnt > -1) return btn[cnt].value;
		else return null;
	}
	
	function popTermosUso(termo){
	  var win = window.open(termo,'','width=706,height=500,scrollbars=yes,top=0,left=0,status=no,toolbar=yes,menubar=no,location=no,resizable=no');
	}
	//----------------------------------------------------
    //-- Método sincrono para a chamada do Ajax
	//-- ( o browser fica aguardando a resposta )
	//----------------------------------------------------

    var http_request_sync = false;
    function getRequestSync(url) {

        http_request_sync = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
			http_request_sync = new XMLHttpRequest();

            if (http_request_sync.overrideMimeType) {
                http_request_sync.overrideMimeType('text/xml');
                // See note below about this line
            }

        } else if (window.ActiveXObject) { // IE
            try {
                http_request_sync = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request_sync = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request_sync) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }

        http_request_sync.onreadystatechange = dummyFunction;
        http_request_sync.open('GET', url, false);
        http_request_sync.send(null);
		return (http_request_sync.responseText);

	}

    function dummyFunction() {

	}
/*FIM ATUALIZA CADASTRO*/

/*COMEÇO ALTERAÇÃO SENHA*/
	function ValidaCampo(c,m) {
		if (c.value=="") {
			alert(m);
			c.focus();
			return false;
		}
		return true;
	}
	function ValidateNewPwd(frm) {
		if (!ValidaCampo(frm.pwd, "Informe a senha atual")) return false;
		if (!ValidaCampo(frm.newpwd, "Informe a nova senha")) return false;
		if (!ValidaCampo(frm.confpwd, "Informe a confirmação da senha")) return false;
		
		if (frm.newpwd.value!=frm.confpwd.value) {
			alert("Nova senha não confere");
			frm.newpwd.value = "";
			frm.confpwd.value = "";
			frm.newpwd.focus();
			return false;
		}
		frm.submit();
		return true;
	}
/*FIM ALTERAÇÃO SENHA*/

/*passo-a-passo*/
var fadeOpacity  = new Array();
var fadeTimer    = new Array();

function fade(o,d,fadeInterval) {
  // o - Object to fade in or out.
  // d - Display, true =  fade in, false = fade out
  var obj = document.getElementById(o);

  if((fadeTimer[o])||(d&&obj.style.display!='block')||(!d&&obj.style.display=='block')) {
    if(fadeTimer[o])
      clearInterval(fadeTimer[o]);
    else
      if(d) fadeOpacity[o] = 0;
      else  fadeOpacity[o] = 9;
  
    obj.style.opacity = "."+fadeOpacity[o].toString();
    obj.style.filter  = "alpha(opacity="+fadeOpacity[o].toString()+"0)";
    
    if(d) {
      obj.style.display = 'block';
      fadeTimer[o] = setInterval('fadeAnimation("'+o+'",1);',fadeInterval);
    } else
      fadeTimer[o] = setInterval('fadeAnimation("'+o+'",-1);',fadeInterval);
  }
  
  if (o == "popFadePasso-a-passo2"){
	  corpo_flash = $('corpo_flash_passo_a_passo_import');
	  corpo_flash2 = $('corpo_flash_passo_a_passo_import2');
	  if (corpo_flash != null){
		corpo_flash.style.display = 'none'; 	  	
	  }	  
	  if (corpo_flash2 != null){
		corpo_flash2.style.display = 'block'; 	  		
	  }
  }
}

function fadeAnimation(o,i) {
  // o - o - Object to fade in or out.
  // i - increment, 1 = Fade In

  var obj = document.getElementById(o);
  fadeOpacity[o] += i;
  obj.style.opacity = "."+fadeOpacity[o].toString();
  obj.style.filter  = "alpha(opacity="+fadeOpacity[o].toString()+"0)";

  if((fadeOpacity[o]=='9')|(fadeOpacity[o]=='0')) {
    if(fadeOpacity[o]=='0')
      obj.style.display = 'none';
    else {
		if (obj.id == "FaderInativo"){
		  obj.style.opacity = "0.6";
		  obj.style.filter  = "alpha(opacity=60)";
		}else{
		  obj.style.opacity = "1";
  		  obj.style.filter  = "alpha(opacity=100)";
		}
    }

    clearInterval(fadeTimer[o]);
    delete(fadeTimer[o]);
    delete(fadeTimer[o]);
    delete(fadeOpacity[o]);
  }  
}

function setFlashPassoAPasso(tipo){
	if (tipo == "F"){
		$('corpo_flash_passo_a_passo_import').innerHTML = SendRequestResponse("/includes/passo_a_passoFlickr2.asp");						
	}else{
		$('corpo_flash_passo_a_passo_import').innerHTML = SendRequestResponse("/includes/passo_a_passoPicasa.asp");
	}
	$('corpo_flash_passo_a_passo_import').style.display = 'block';
	$('corpo_flash_passo_a_passo_import2').style.display = 'none';
}