// VALIDATORS
function CheckValidators(groupID,cssClass, funcStyle)
{
    Page_ClientValidate(groupID);
    var controlsAlreadyValidated = new Array();
    var changeStyleFunc;
    if (funcStyle){
        changeStyleFunc = funcStyle;
    }
    else
    {
        changeStyleFunc = ChangeControlStyle;
    }
          
    for (var i = 0; i < Page_Validators.length; i++) {
          var control = Page_Validators[i].controltovalidate;
          if($.inArray(control, controlsAlreadyValidated) == -1) 
          {
                changeStyleFunc(control,Page_Validators[i].isvalid,cssClass);
                if(!Page_Validators[i].isvalid){
                      controlsAlreadyValidated.push(control);
                }
          }
    }
}

function ChangeControlStyle(id, isvalid, cssClass)
{    
      if(!isvalid)
      {
        $('#'+id).addClass(cssClass);
      }
      else
      {
        $('#'+id).removeClass(cssClass);
      }
}

//Função para customValidators (usa o validator.display em ves de isValid)
function CheckFormCustomValidators(groupID,cssClass,errorblockid)
{
    var controlsAlreadyValidated = new Array();
    var errorMessage = ''; 
    var allValid = true;
    
    for (var i = 0; i < Page_Validators.length; i++) {
          var control = Page_Validators[i].controltovalidate;
          var validator = Page_Validators[i];
          
          if($.inArray(control, controlsAlreadyValidated) == -1 && validator.validationGroup == groupID ) 
          {
                ChangeFormControlStyle(control,Page_Validators[i].isvalid,cssClass,errorblockid);
                //if(validator.display == 'Dynamic')
                if($('#'+validator.id).is(":visible"))
                {
                      $('#'+validator.id).hide();
                      allValid = false;
                      controlsAlreadyValidated.push(control);   
                      if (validator.errormessage)
                        errorMessage = errorMessage + validator.errormessage + '<br/>';                                       
                }
          }
    }    
    
    if (allValid)
    {
        $('#'+errorblockid).hide('fast');
    }
    else
    {                       
        $('#' + errorblockid).html(errorMessage).fadeIn(3000);                
    }                
}

function CheckFormValidators(groupID,cssClass,errorblockid)
{
    Page_ClientValidate(groupID);
    var controlsAlreadyValidated = new Array();
    var errorMessage = ''; 
    var allValid = true;
    
    for (var i = 0; i < Page_Validators.length; i++) {
          var control = Page_Validators[i].controltovalidate;
          var validator = Page_Validators[i];
          
          if($.inArray(control, controlsAlreadyValidated) == -1 && validator.validationGroup == groupID ) 
          {
                ChangeFormControlStyle(control,Page_Validators[i].isvalid,cssClass,errorblockid);
                if(!Page_Validators[i].isvalid )
                {
                      allValid = false;
                      controlsAlreadyValidated.push(control);   
                      if (validator.errormessage)
                        errorMessage = errorMessage + validator.errormessage + '<br/>';                                       
                }
          }
    }    
    
    if (allValid)
    {
        $('#'+errorblockid).hide('fast');
    }
    else
    {                       
        $('#' + errorblockid).html(errorMessage).fadeIn(3000);                
    }                
}
                   
function ChangeFormControlStyle(controlid, isvalid, cssClass,errorblockid)
{    
    if(!isvalid)
    {
        $('#'+controlid).parent().addClass(cssClass);                    
    }
    else
    {
        $('#'+controlid).parent().removeClass(cssClass);                  
    }
}  


/*
 * Addthis 0.1
 * (c)2009 Brent Wong
 * 
 * Usage:
 *  $.addthis();
 *   -or-
 *  $.addthis('username');
 *  where username is your AddThis username. Useful for tracking statistics

 *(function($){
 *     $.addthis = function(code){
 *
 *            function init(){
 *                  try{
 *                        // determine whether to include the normal or SSL version
 *                        var addthisurl = (location.href.indexOf('https') == 0 ? 'https://' : 'http://') + 's7.addthis.com/js/250/addthis_widget.js?pub=' + code;
 *
 *                        // include the script
 *                        $.getScript(addthisurl, function(){
 *                             $('a.addthis').append('<img src="http://s7.addthis.com/static/btn/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/>').attr('href', 'http://www.addthis.com/bookmark.php?v=250').mouseover(
 *                                   function(){
 *                                         return addthis_open(this, '', '[URL]', '[TITLE]');
 *                                   }).mouseout(
 *                                   function(){
 *                                         addthis_close();
 *                                   }).click(
 *                                   function(){
 *                                         return addthis_sendto();
 *                                   });
 *                        });
 *                  } catch(err) {
 *                        // log any failure
 *                        console.log('Failed to load AddThis Script:' + err);
 *                 }
 *            }
 *
 *            init();
 *      }
 *})(jQuery);
*/


function HoverImgOf(filename)
{
   var re = new RegExp("(.+)\\.(gif|png|jpg)", "g");
   return filename.replace(re, "$1_hi.$2");
}


function NormalImgOf(filename)
{
   var re = new RegExp("(.+)_hi\\.(gif|png|jpg)", "g");
   return filename.replace(re, "$1.$2");
}



jQuery.fn.resetDefaultValue = function() {
	function _clearDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == this.defaultValue ) { _$.val(''); }
	};
	function _resetDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == '' ) { _$.val(this.defaultValue); }
	};
	return this.click(_clearDefaultValue).focus(_clearDefaultValue).blur(_resetDefaultValue);
}



// columns equal height
function setEqualHeight(columns) {  
	var tallestcolumn = 0;  
	columns.each(  
	function() {  
		currentHeight = $(this).height();  
		if(currentHeight > tallestcolumn) {  
			tallestcolumn  = currentHeight;  
		}  
	});  
	
	columns.height(tallestcolumn);  
} 

function EscondeRoller(bitHide)
{
    var divroller = $("#flashcontent3");
    var divsombra = $(".second");
    var tituloroller = $("#TituloRoller");
    
	if(bitHide)
	{
	    divroller.each(  
	    function() {
	        tituloroller.css("display","block");
	        divroller.css("visibility","visible");
	        divsombra.css("visibility","visible");
	        divroller.height(150);
	        divsombra.hidden(150);
	    });
	}
	else
	{
	    divroller.each(  
	    function() {
	        tituloroller.css("display","none");
	        divroller.css("visibility","hidden");
	        divsombra.css("visibility","hidden");
	        divroller.height(0);
	        divsombra.hidden(0);
	    });
	}
}

/* Funcoes para o flash topo */

function hideDivVantagens()
{
	document.getElementById("divBanner").style.display="none";
	document.getElementById("divBanner").style.visibility="hidden";
	//getElementById("vantagens").gotoAndPlay(1);
	//alert("fechado");
}

function showDivVantagens()
{
	//document.getElementById("divBanner").style.display="block";
	//document.getElementById("divBanner").style.visibility="visible";
	//getFlashMovieObject("vantagens2").gotoFrame();
	window.location="/novosocio";

	//alert("fechado");
}

/* --Funcoes para o flash topo */

/* EMBED - used by TinyMCE */

function writeFlash(p) {
	writeEmbed(
		'D27CDB6E-AE6D-11cf-96B8-444553540000',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
		'application/x-shockwave-flash',
		p
	);
}

function writeShockWave(p) {
	writeEmbed(
	'166B1BCA-3F9C-11CF-8075-444553540000',
	'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0',
	'application/x-director',
		p
	);
}

function writeQuickTime(p) {
	writeEmbed(
		'02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
		'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
		'video/quicktime',
		p
	);
}

function writeRealMedia(p) {
	writeEmbed(
		'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
		'audio/x-pn-realaudio-plugin',
		p
	);
}

function writeWindowsMedia(p) {
	p.url = p.src;
	writeEmbed(
		'6BF52A52-394A-11D3-B153-00C04F79FAA6',
		'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701',
		'application/x-mplayer2',
		p
	);
}

function writeEmbed(cls, cb, mt, p) {
	var h = '', n;

	h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
	h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
	h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
	h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
	h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
	h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
	h += '>';

	for (n in p)
		h += '<param name="' + n + '" value="' + p[n] + '">';

	h += '<embed type="' + mt + '"';

	for (n in p)
		h += n + '="' + p[n] + '" ';

	h += '></embed></object>';

	document.write(h);
}


/* end EMBED - used by TinyMCE */ 

// Pre-load images
jQuery.fn.preLoadHover = function() {
    var re_hi = new RegExp("(.+)\\.(gif|png|jpg)", "g");
    var cache_nav_hi = [];
    
    $(this).each(function() {
        var filename = $(this).attr("src");	    
        var cacheImage = document.createElement('img');
        cacheImage.src = filename.replace(re_hi, "$1_hi.$2");
        cache_nav_hi.push(cacheImage);
    });
}


/* Destaques homepage AJAX */

// URLENCODE FUNCTION
function URLEncode(str){
	var histogram = {}, tmp_arr = [];
	var ret = (str+'').toString();

	var replacer = function(search, replace, str){
	var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};

	// The histogram is identical to the one in urldecode.
	histogram["'"]   = '%27';
	histogram['(']   = '%28';
	histogram[')']   = '%29';
	histogram['*']   = '%2A';
	histogram['~']   = '%7E';
	histogram['!']   = '%21';
	histogram['%20'] = '+';
	histogram['\u20AC'] = '%80';
	histogram['\u0081'] = '%81';
	histogram['\u201A'] = '%82';
	histogram['\u0192'] = '%83';
	histogram['\u201E'] = '%84';
	histogram['\u2026'] = '%85';
	histogram['\u2020'] = '%86';
	histogram['\u2021'] = '%87';
	histogram['\u02C6'] = '%88';
	histogram['\u2030'] = '%89';
	histogram['\u0160'] = '%8A';
	histogram['\u2039'] = '%8B';
	histogram['\u0152'] = '%8C';
	histogram['\u008D'] = '%8D';
	histogram['\u017D'] = '%8E';
	histogram['\u008F'] = '%8F';
	histogram['\u0090'] = '%90';
	histogram['\u2018'] = '%91';
	histogram['\u2019'] = '%92';
	histogram['\u201C'] = '%93';
	histogram['\u201D'] = '%94';
	histogram['\u2022'] = '%95';
	histogram['\u2013'] = '%96';
	histogram['\u2014'] = '%97';
	histogram['\u02DC'] = '%98';
	histogram['\u2122'] = '%99';
	histogram['\u0161'] = '%9A';
	histogram['\u203A'] = '%9B';
	histogram['\u0153'] = '%9C';
	histogram['\u009D'] = '%9D';
	histogram['\u017E'] = '%9E';
	histogram['\u0178'] = '%9F';

	// Begin with encodeURIComponent, which most resembles PHP's encoding functions
	ret = encodeURIComponent(ret);

	for(search in histogram){
		replace = histogram[search];
		ret = replacer(search, replace, ret) // Custom replace. No regexing
	}

	// Uppercase for full PHP compatibility
	return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2){
		return "%"+m2.toUpperCase();
	});

	return ret;
}

function LoadData(url, navLink)
{
	/*var pageurl= window.location.href;
	if (pageurl.indexOf("#") != -1) 
	{
    	pageurl = window.location.href.split("#")[0];
    }*/
    
    //url += ((url.indexOf("?") != -1) ? '&' : '?') + 'pageurl=' + URLEncode(pageurl);
        
    //$(".DestaquesContainer").html("<div class='loading'><img src='/design/images/loading.gif' /></div>");
    $(".DestaquesContainer").load(url, function(response, status, xhr) {
        $(this).hide().fadeIn(1500);
        $("ul.TemasList .Item").removeClass('active');
	    $(navLink).toggleClass('active');
    });
}

function LoadRollerData (url)
{
    $(".SmallWidth").load(url, function(response, status, xhr) {
        $(this).hide().fadeIn(1500);
    });
}


function slide(){
    $('.nextColumn a').click();
}

var intervalId = window.setInterval(slide, 4000);

/*  */
$(document).ready(function(){ 

    $(".imgnav").preLoadHover();

	// columns equal height
	setEqualHeight($(".column1-2 .spc"));
	setEqualHeight($(".map-list .top > li"));
	setEqualHeight($(".map-list .bottom > li"));
	//setEqualHeight($(".list-products-spc"));	
	
	// clean value inputs
	$('input.clean').resetDefaultValue(); // avoid button/reset/submit buttons
	
	//site map animation
	
	
	if($('#map-list').length){
	    
	    $('#map-list').slideUp();
	    $('#site-map-hand').attr("title", see);
		
	    $('#site-map-hand-top').click(function (event) {	
		    if ($("#map-list").is(":hidden")) { 
			    $("#map-list").slideDown();
			    $('#site-map-hand').addClass('close');
			    $('#site-map-hand').attr("title", close);
		    }				
        });	
    	
	    $('#site-map-hand').click(function () {		
		    if ($("#map-list").is(":hidden")) {
			    $("#map-list").slideDown('fast');
			    $(this).addClass('close');
			    $('#site-map-hand').attr("title", close);
    			
		     } else {
			    $("#map-list").slideUp();
			    $(this).removeClass('close');
			    $('#site-map-hand').attr("title", see);
		     }
        });
    }		

	//login
	 $('#login-handler').css('cursor','pointer');
	if (((typeof(authenticated) != 'undefined') || (typeof(loginError) != 'undefined')) &&
	    !((typeof(authenticated) == 'undefined') && (typeof(loginError) == 'undefined')))
	{	
	    if(typeof(authenticated) != 'undefined')
	    {
	        if (!authenticated)
	        {
	            $('#nav-top-box').hide();
	        }
	        else 
	        {
	            $('#nav-top-box').show();
	            $('#login-handler').addClass('close');
	        }
	    }
	    if(typeof(loginError) != 'undefined')
	    {
	        if (!loginError)
	        {
	            $('#nav-top-box').hide();
	        }
	        else 
	        {
	            $('#nav-top-box').show();
	            $('#login-handler').addClass('close');
	        }
	    }
	    
	}
	else
	{  
	    $('#nav-top-box').hide();
	}
	
	$('#login-handler').click(function () {
      $('#nav-top-box').toggle();
	  $(this).toggleClass('close');
    });

	
	/* nav img hover */
	$(".imgnav").hover( function() {
	   var hoverImg = HoverImgOf($(this).attr("src"));
	   $(this).attr("src", hoverImg);
	 }, function() {
	   var normalImg = NormalImgOf($(this).attr("src"));
	   $(this).attr("src", normalImg);
	 }
	);
	
	
	/* hover nivel 3 */
	$("#nav .nivel3").slideUp(100);
	
	$("#nav .nivel2 ul > li").hover( function() {
		$(this).find(".nivel3").stop(true, true).slideDown(200);
		$(this).addClass("active");			
	 }, function() {
		$(this).find(".nivel3").slideUp(100);
		$(this).removeClass("active");
	 }
	);
	
	// partilha
	//$.addthis()
	
	/* resultados descontos */
	var hideDivs = $(".results-descontos > ul > li .descrition");
	hideDivs.hide();
	var hrefText = $(".results-descontos > ul > li .text a");
	
	$(hrefText).click(function (){
		var full_url = $(this).attr('href');
		if( $(full_url).is(':hidden') ){
			hideDivs.hide();
			hrefText.removeClass("active");
			$(this).toggleClass("active");
			$(full_url).fadeIn();
		} else {
			hrefText.removeClass("active");
			$(full_url).fadeOut();
		}
		return false;
	});

	/* Galeria de revistas */
	$(".galleryButtons").hide();
	$(".magazineGalleryRow ul li").hover(
		function () {
			$(this).find(".galleryButtons").show();
			return true;
    },
		function () {
			$(this).find(".galleryButtons").hide();
		}
	);
	
	$('a.hideMessage').click(function(){
	    $('.partnerSucesso').hide();
	});
		
	if($('.cycleDestaques') != null && $('.cycleDestaques').children().length > 1)
	{	
        $('.cycleDestaques').cycle({
	            fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
	            //next: '.nextColumn .next',
	            //prev: '.prevColumn .prev',
	            timeout: 0,
	            pager: '#cycleNavigation'
        });
	    
	    $('.DestaquesContainer').height($('.cycleDestaques .Item').height());
	};
	
	if($('.cycleRoller') != null && $('.cycleRoller').children().length > 1)
	{
	    $('.cycleRoller').each(function(){
            var $this = $(this);

            $this.cycle({
	                fx: 'scrollHorz', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
	                next: $this.next('.nextColumn').find('.next'),
                    prev: $this.prev('.prevColumn').find('.prev'),
	                speed:  'slow', 
	                prevNextEvent: 'mouseover click',
	                timeout: 0/*,
	                pager: '#cycleNavigation'*/
            });
        });
	};
	
	$("ul.TemasList .Item").live('click',function () {
	    LoadRollerData("/RollerHomepageAjax.aspx" + $(this).attr('href'));
	    LoadData("/DestaquesHomepageAJAX.aspx" + $(this).attr('href'), this);	    
	    return false;
	});
	
    $('.prevColumn a, .nextColumn a').click(
     function(event){
      if(event.originalEvent){
       //window.clearInterval(intervalId);
      }
     }
    );

    $('.viewport > div .Item').mouseover(function() {
        window.clearInterval(intervalId);
    });
    $('.viewport > div .Item').mouseout(function() {
        intervalId = window.setInterval(slide, 4000);
    });    
});
