﻿$(function() {
	
	autoCloseLayer();		
	
	$('.botao-revista').click(function(){
		track('/site/revista-gremio');
	});
	
    //se for home
    if ($("ul#products").length && $("#antena-tricolor").length) {
        var target, name, price, thumb;
        $.get(rootUrl + "xml/gremiomania_xml.aspx", function(data) {
            $(data).find("product").each(function() {
                target = $(this).attr("target");
                thumb = $(this).attr("thumb");
                price = $(this).attr("price");
                name = $(this).attr("name");

                $("ul#products").append("<li><a href='" + target + "'><img src='" + thumb + "' width='79' alt='" + name + "'/></a><a href='" + target + "' class='price'>" + price + "</a><a href='" + target + "' class='link'>Compre</a><br /></li>");
            });
            $("#products").jcarousel();
        });

        $("#antena-tricolor input.name").focus(function() {
            if ($(this).val() == "Nome") {
                $(this).val("")
            }
        })
        $("#antena-tricolor input.name").blur(function() {
            if ($(this).val() == "") {
                $(this).val("Nome")
            }
        })

        $("#antena-tricolor input.email").focus(function() {
            if ($(this).val() == "E-mail") {
                $(this).val("")
            }
        })
        $("#antena-tricolor input.email").blur(function() {
            if ($(this).val() == "") {
                $(this).val("E-mail")
            }
        })


        $.get(rootUrl + "xml/highlight_xml.aspx?type=highlight&language=" + language, function(response) {
            $(response).find("highlight").each(function() {
                var type = $(this).find("type").text();
                var title = $(this).find("title").text();
                var link = $(this).find("link").text();
                var file = $(this).find("file").text();

                if (type != "swf") {
                    $("#destaque_flash ul").append("<li><a href='" + link + "'><img src='" + rootUrl + file + "' alt='" + title + "' />" + "</a>" + "<a class='title' href='" + link + "'>" + wrapTitle(title) + "</a>" + "</li>");
                } else if (mmLink && gameName) {
                    $("#destaque_flash ul").append("<li><a id='minuto-a-minuto'></a></li>");
                    var sos = new SWFObject("../" + file, "destaques", "670", "250", "8");
                    sos.addParam("quality", "high");
                    sos.addParam("wmode", "transparent");
                    sos.addVariable("mm_link", mmLink);
                    sos.addVariable("game_name", gameName);
                    sos.addVariable("language", language);
                    sos.write("minuto-a-minuto");

                    $("#minuto-a-minuto").attr("href", mmLink).fancybox({
                        'frameWidth': 720,
                        'frameHeight': 440
                    });

                }
            })
            $("#destaque_flash ul a.title").each(function() {
                $(this).css({ "top": 125 - (Math.round($(this).height() / 2)) });
            });

            $("#destaque_flash ul").cycle({
                fx: 'fade',
                speed: 1000,
                timeout: 8000,
                pager: '#highlight-paginate'
            });
        }, 'xml');
    }
    $("#search input.keyword").focus(function() {
        if ($(this).val() == "/ busca" || $(this).val() == "/ search") {
            $(this).val("");
        }
    });
    if ($("#search input.keyword").val() == "/ busca") {
        $("#search input.keyword").blur(function() {
            if ($(this).val() == "") {
                $(this).val("/ busca");
            }
        });
    } else if ($("#search input.keyword").val() == "/ search") {
        $("#search input.keyword").blur(function() {
            if ($(this).val() == "") {
                $(this).val("/ search");
            }
        });
    }


    $("#gremio-tv").click(function() {
        $("#radio").hide();
        $("#gremio-radio").removeClass("selected");
        $($(this).attr("href")).show();
        $(this).addClass("selected");
        return false;

    });
    $("#gremio-radio").click(function() {
        $("#tv").hide();
        $("#gremio-tv").removeClass("selected");
        $($(this).attr("href")).show();
        $(this).addClass("selected");
        return false;
    });


    //menu
    $("#nav li.nav-item:has(div.layer:has(ul))").hover(
		function() {
		    $(this).find(".layer").show();
		},
		function() {
		    $(this).find(".layer").hide();
		}
	);

    $("#nav li.nav-item div.layer").each(function(index, elm) {
        $(elm).width($(elm).find("ul").length * 180);
    });


    $("#nav div.layer:has(.highlight)").addClass("nav-highlight");

    $("#header-nav li.login a").click(
		function() {
		    $(this).toggleClass("active");
		    $("#header-login").slideToggle("fast");
		}
	);

    if ($("#login_name").length) {
        $("#header-nav li.login a").addClass("active");
    } else {
        $("#header-login").hide();
    }


    if ($("#submenu").height() > $("#content").height()) {
        $("#page-view").height($("#submenu").height() - 150)
    }

    $("a[rel='print']").click(function() {
        window.print();
    });

    $("a[rel='back']").click(function() {
        history.go(-1);
    });

    $("a[rel='external']").attr("target", "_blank");

    $("#nav li a[rel='parent']").addClass("parent");

    if ($(".nav-item > a.active").length) {
        $(".nav-item > a:not(.active)").addClass("off")
    }

    $("table.tablelist tr:odd").addClass("row");

    if ($("#noticias .description div.text").length) {
        $("a.fancybox").fancybox();
    }
    
    $('input.keyword').keypress(function(e){
	    if (e.which == 13) {
	        if (!$(this).val() || $(this).val() == "/ busca" || $(this).val() == "/ search") {
	            alert("Digite palavras chave para efetuar a busca.");
	            return false;
	        }
	    }
	});
	
	$('input.search-button').click(function(){
	    if (!$('input.keyword').val() || $('input.keyword').val() == "/ busca" || $('input.keyword').val() == "/ search") {
            alert("Digite palavras chave para efetuar a busca.");
            return false;
        }
	});
	
	$('#content div.covenant-content input').keypress(function(e){
	    if (e.which == 13) {
	        return false;
	    }
	});
	$('#right-submenu input').keypress(function(e){
	    if (e.which == 13) {
	        return false;
	    }
	});

});

function openWindow(url) {
     x = window.open(url,'_blank','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=auto,resizable=yes,copyhistory=no');
	 x.focus();
}

function openPopup(_url,_winName,_width,_height,_scroll,_return) {
	var _y = (screen.height - _height) / 2;
	var _x = (screen.width - _width) / 2;
    var x = window.open(_url,_winName,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars='+_scroll+',resizable=no,copyhistory=no,top='+_y+',left='+_x+',screenY='+_y+',screenX='+_x+',width='+_width+',height='+_height);
	x.focus();
	if (_return)
	    return x;
}

function clickButton(e, buttonid) {    
	var bt = document.getElementById(buttonid);
    
    if (e.currentTarget.type == 'textarea') {
        return;
    }    

	if(bt.tagName == "A") {
		if (e.keyCode == 13) {
			location.href = bt.href;
			return false;
		}
	}
	else {
		if (typeof bt == 'object') {		    
		    if (e.keyCode == 13) {
			    bt.click(); 
			    return false; 
		    }			
		}
	}

}

function handleEnter (field, event) {
       var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) 
                return false;
    }  

var prev;
function MyTDColor(tableRow, highLight) {
	if (highLight) {
		prev = tableRow.style.backgroundColor;
		tableRow.style.backgroundColor = '#00AEEF';
		tableRow.style.cursor = 'pointer';
	}
	else {
		tableRow.style.backgroundColor = prev;
		tableRow.style.cursor = 'auto';
	}
}

function TDNav(TDUrl) {
	document.location.href = TDUrl;
}

function showFields(div, checked) {
    var ph = document.getElementById(div);
    ph.style.display = (checked ? "block" : "none");
    ph.style.visibility = (checked ? "visible" : "hidden");
}

String.prototype.wordWrap = function(m, b, c) {
    var i, j, l, s, r;
    if (m < 1)
        return this;
    for (i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
        for (s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
        j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
			|| c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    return r.join("\n");
};

String.prototype.trim = function(){
    return this.replace(/^\s+|\s+$/g,"");
}


function wrapTitle(title) {
    var wrapText = title.wordWrap(15, "\n", true);
    var sentence = wrapText.split("\n");

    var wrapped = "";
    for (i in sentence) {
        if (i != sentence.length - 1) {
            wrapped += "<span>" + sentence[i].trim() + "</span><br />";
        }
        else {
            wrapped += "<span>" + sentence[i].trim() + "</span> ";
        }
    }
    return wrapped;
}

$(document).ready(function(){
	$('#layer #video').hide();
	$('#layer').fadeIn(1500,
		function() {
			$('#layer #video').fadeIn(2500);
		});
		
	$('#overlay, .fechar').click(function() {
		track('/site/layer/fechar');
		$('#layer').fadeOut(1500);
	});
});

function closeLayer(skipTrack){
	if (skipTrack != true) {
		track('/site/layer/fechar');
	}
    $('#layer').fadeOut(1500);
}



$(document).ready(function(){
	$('#listToggle li div').addClass('hide');
	$('#listToggle li a.linkToggle').click(function() {
		if ($(this).next().is('div:visible')) {
			return false;
		}
		$('#listToggle li div:visible').slideToggle();
		$(this).next().slideToggle('slow');
		return false;
	});
	
});

$(document).ready(function(){
	$('.none').addClass('hide');
	$('p.openList').click(function() {
		$(this).next().slideToggle('slow');
		return false;
	});
	
});

function autoCloseLayer() {	
	setTimeout('closeLayer(true)',20000);
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

$(document).ready(function() {
	$('.quant-img a').click(function(event) {			
		event.preventDefault();
		if (!$('.bgimgs img').is(':animated')) {				
			var link = this.href;
			
			$('.quant-img a.corrente').removeClass("corrente");
			$(this).addClass("corrente");
			setImage(link);				
		}
	});
	$('.proximo').click(function(){
		var link = $('.corrente').parent().next().find('a');			
		if (link.length) {
			$('.quant-img a.corrente').removeClass("corrente");
			link.addClass("corrente");
			setImage(link.attr('href'));
		}
	});
	$('.anterior').click(function(){
		var link = $('.corrente').parent().prev().find('a');			
		if (link.length) {
			$('.quant-img a.corrente').removeClass("corrente");
			link.addClass("corrente");
			setImage(link.attr('href'));
			var image = $('<img>').attr('src',link.attr('href')).load(function(){
				$('.bgimgs').find('img').remove().end().append(image);
				$(this).css('opacity', '0.3').stop().animate({opacity: 1 }, 1500);				
			});				
		}
	});
	
	function setImage(link) {
		image = $('<img>').attr('src',link).load(function(){
			$('.bgimgs').find('img').remove().end().append(image);
			$(this).css('opacity', '0.3').stop().animate({opacity: 1 }, 1500);				
		});
	}
});
