var tempTitle = null;
var t = null;
var s;  // siteCatalyst tracking
var providers = ["dr-store.avast.com","store.avast.com"];  // HADD specification

var TT_FADE_IN_SPEED = 300;
var TT_HIDE_DELAY = 150;
var TT_SHOW_DELAY = 550;
var TT_ARROW_HEIGHT = 30;
var TT_LEFT_DIS = 30;
var vocabulary = "tooltip.php"; 
var searchTerm, searchRegex, xmlTooltip, tt;

$(document).ready(function(){	
	/*Region selector*/ 
    $('.ls').click(function(e){
        ShowLanguageSelector();
        return false;
    });
    $('#close_selector').click(function(){
        HideLanguageSelector();                              
        return false;
    });
    /*END Region selector*/
    
    /*Counter*/
    
    if($(".counter-value").length > 0 && $("#home").length == 0) 
    {
        $(".counter-value").each(function(){
            SetCounter($(this));
        });
    }
    
    /*END Counter*/
    
    /*tracking*/
    
        $("a").each(function(){
            if($(this).attr('href') != undefined) {
                if(($(this).attr('href').indexOf('store.avast.co.jp') != -1 && $(this).attr('onclick') == undefined) || ($(this).attr('href').indexOf('dr-store.avast.com') != -1 && $(this).attr('onclick') == undefined)){
                    $(this).click(function(e){
                        //alert($(this).attr('href'));
                        var url = $(this).attr('href');
                        pageTracker._link(url);
                        e.preventDefault();
                        return false;
                    });
                }
            }
        });
    
    /*END ja-jp tracking*/
        
    /* HADD */
    HandleHADD();
    /* END HADD */
	
	/* Tooltips */
	if(document.URL.indexOf("int-pt-v6-ise01-radio") == -1)
	{
		$.ajax({
			type: "POST",
			url: RootPath+vocabulary,
			//url: RootPath+"languages/glossary."+locale+".xml",
			cache: false,
			data: "locale="+locale,
			dataType: ($.browser.msie)? "text": "html",
			success:function(data){
				if ($.browser.msie) {
				   xmlTooltip = new ActiveXObject("Microsoft.XMLDOM");
				   xmlTooltip.async = false;
				   xmlTooltip.loadXML(data);
				 } else {
				   xmlTooltip = data;
				 }
				 var imgPreload = "<img src='http://static.avast.com/web/i/tooltip-bg.png' style='display:none' />" +
				                  "<img src='http://static.avast.com/web/i/tooltip-pointer.png' style='display:none' />" +
								  "<img src='http://static.avast.com/web/i/tooltip-top.png' style='display:none' />" +
								  "<img src='http://static.avast.com/web/i/tooltip-grad.png' style='display:none' />" +
								  "<img src='http://static.avast.com/web/i/tooltip-bottom.png' style='display:none' />";
				 $("body").append(imgPreload);
				HandleTooltips();
			}
		});
	}
	
	$(".tooltip-w").live('mouseover',function(e){
		var kkey = $(this).attr('vocw');
		if(tt != null){
			clearTimeout(tt);
		}
		tt = setTimeout(function(){showTooltip(e,kkey);}, TT_SHOW_DELAY);
	});
	$(".tooltip-w").live('mouseout',function(e){
		if(tt != null){
			clearTimeout(tt);
		}
		tt = setTimeout('hideTooltip()', TT_HIDE_DELAY);
	});
	$("#tooltip").live('mouseover',function(e){
		if(tt != null){
			clearTimeout(tt);
		}
	});
	$("#tooltip").live('mouseout',function(e){
		if(tt != null){
			clearTimeout(tt);
		}
		tt = setTimeout('hideTooltip()', TT_HIDE_DELAY);
	});
	/* END Tooltips */
});    

function HandleHADD(){
    var name = "hadd";
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS,"i");
    var results = regex.exec(window.location.href);
    if(results == null)
        return 1;
    else
        var i;
        var href;
        var param;
        $("a").each(function(){
            href = $(this).attr('href');
            for(i=0;i<providers.length;i++){
                if(href.indexOf(providers[i]) != -1){
                    if(i == 0){
						var regIDS = "[\\?&]PRODUCT([^&#=]*)";
						var regID = new RegExp(regIDS,"i");
						var ids = regID.exec(href);
						if(ids == null){}
						else{
							param = "HADD"+ids[1]+"[ADDITIONAL1]="+results[1];
							if(href.indexOf("?") == -1)
								href = href + "?" + param;
							else
								href = href + "&" + param;
							$(this).attr('href',href);
						}
					}
					else if(i == 1){
						var regIDS = "productID[\.]([^&#=\/]*)[\/]";
						var regID = new RegExp(regIDS,"i");
						var ids = regID.exec(href);
						if(ids == null){}
						else{
							param = "/HADD."+ids[1]+"/ADDITIONAL1."+results[1];
							href = href + param;
							$(this).attr('href',href);
						}
					}
                }
            }
        });
}

function HandleTooltips(){
	var home = false;
	if($("#home").length > 0){
		home = true;
	}
	$(xmlTooltip).find('i').each(function(){
		searchTerm = $(this).attr('title');
		searchRegex  = new RegExp("(^\|[ \n\r\t.,'\"\+!?-]+)("+searchTerm+")([ \n\r\t.,'\"\+!?-]+\|$)", "gi");
		if(home){
			//$("#home *").replaceText( searchRegex, '<span class="tooltip-w" vocw="'+searchTerm+'">$2</span>');
		}
		else{
			$("#content-holder *:not(#tabs-navigation *)").replaceText( searchRegex, '$1<span class="tooltip-w" vocw="'+searchTerm+'" style="font-size:inherit !important; font-weight:inherit !important; color:inherit !important; cursor:help !important; padding:0 !important;	margin:0 !important; border-bottom:1px dotted #000 !important; display:inline !important;">$2</span>$3');
		}
	});
}

function showTooltip(e,kkey){
	var to = $(e.target);
	var key = kkey;
	var cHolder = $("#content-holder");
	var cTop = cHolder.offset().top;
	var cLeft = cHolder.offset().left;
	
	var top = to.offset().top - cTop + to.outerHeight() + TT_ARROW_HEIGHT/2;
	var left = to.offset().left - cLeft - TT_LEFT_DIS;
	$("#tooltip").remove();
	
	var tDiv = "<div id=\"tooltip\" style='position: absolute;z-index: 9998;width: 271px ;background: transparent url(http://static.avast.com/web/i/tooltip-bg.png) left top repeat-y;'>"+
					"<img src=\"http://static.avast.com/web/i/tooltip-pointer.png\" style='position: absolute;left: 30px;top: -19px;z-index: 9999;' />"+
					"<span class=\"tt-top\" style='position: absolute;left: 0px;width: 271px;height: 9px;top: -9px;background: transparent url(http://static.avast.com/web/i/tooltip-top.png) left bottom no-repeat;'></span>"+
					"<em style='font-style:normal;display:block !important;margin: 0px 3px 0px !important;background: #ecedee url(http://static.avast.com/web/i/tooltip-grad.png) left top repeat-x !important;padding: 0px 10px 0px !important;color:#000 !important;font-size:12px !important;font-weight:normal !important;line-height: 16px !important;'></em>"+
					"<span class=\"tt-bottom\" style='position: absolute;left: 0px;width: 271px;height: 9px;bottom: -9px;background: transparent url(http://static.avast.com/web/i/tooltip-bottom.png) left top no-repeat;'></span>"+
				"</div>";
				
	//to.parent().append(tDiv);
	$("#content-holder").append(tDiv);
	
	if($("#"+key).length > 0){
		$("#tooltip em").html($("#"+key).html());
	}else{
		$("#tooltip em").html($(xmlTooltip).find("i[title='"+key+"']").text());
	}
	
	$("#tooltip")
		.css({
			'top':top+"px",
			'left':left+"px"
		})
		.fadeIn(TT_FADE_IN_SPEED);
}

function hideTooltip(){
	$("#tooltip").hide();
}

function ShowLanguageSelector()
{
    var message = $('#lang_selector');
    var scr = "<div id=\"language_lightbox\"></div>";
    
    var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
    var topPosition=document.all? iebody.scrollTop : pageYOffset;
            
    $('body').append(message);
    $('body').append(scr);
    $('#language_lightbox').css({opacity:0,'width':$(document).width(),'height':$(document).height()});
    $('#language_lightbox').css({opacity: 0.8});
    message.show();
    if (!document.all) $('body').css({'overflow':'hidden'});
        
    var leftPosition = ($(document).width()/2)-(message.width()/2);
    message.css({'display': 'block', 'top': topPosition+140, 'left': leftPosition});
    document.body.onscroll = function(e){
        var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
        var topPosition=document.all? iebody.scrollTop : pageYOffset;
        
        message.animate({'top': topPosition +140},1);
    }   
    var img = new Image;
    $(img)
        .load(function(){
            $("#lang_loader").fadeOut(500);
        })
        .attr('src', 'http://static.avast.com/web/i/background-language-selector.jpg');
    
    $('#language_lightbox').click(function(){HideLanguageSelector();});
    
    s=s_gi('avast-dev');
    s.linkTrackVars='eVar4';
    s.pageName='Region Selector';  //overlay pagename
    s.eVar4='D=pageName'
    s.tl(true,'o','D=pageName');  //no time delay
}

function HideLanguageSelector()
{
    var message = $('#lang_selector');
    var scr = $('#language_lightbox');
    message.hide();
    scr.remove();
    if (!document.all) $('body').css({'overflow':'auto'});
}

function SetCounter(el)
{   
    var campaign = el.attr('id');
    var parentID = campaign.substr(1);
    if(campaign != 'undefined'){
        $.ajax({
                type: "POST",
                url: RootPath + "countdown.php",
                cache: false,
                data:"campaign="+campaign,
                beforeSend: function(){
                },
                success: function(html){
                    if(html != "-1")el.html(html);
                    else $("#counter"+parentID).hide();
                },
                error:function(){
                    $("#counter"+parentID).hide();
                }
        });
    }
    //else $("#counter").hide();
}

function setLanguage(lang)
{
    var myDate=new Date();
    myDate.setDate(myDate.getDate() + 365);
    document.cookie = "avastComLocale="+lang+";path=/;EXPIRES=" + myDate.toGMTString();
}

$.fn.expandCollapse = function(el){
	this.live('click',function(e){
		e.preventDefault();
		$(el).slideToggle();
		return false;
	}).css('cursor','pointer');
}



$.fn.replaceText = function( search, replace, text_only ) {
    return this.each(function(){
      var node = this.firstChild,
        val,
        new_val,
        remove = [];
      if ( node ) {
    	do {
        	if ( node.nodeType === 3) {
            val = node.nodeValue;
			new_val = val.replace( search, replace );
            
			if ( new_val !== val ) {
              if ( !text_only && /</.test( new_val ) ) {
                $(node).before( new_val );
                remove.push( node );
              } else {
                node.nodeValue = new_val;
              }
            }
          }
        } while ( node = node.nextSibling );
      }
      remove.length && $(remove).remove();
    });
  };  
 
 jQuery.fn.removeHighlight = function() {
	 return this.find("span.tooltip").each(function() {
		  with (this.parentNode) {
				replaceChild(this.firstChild, this);
		  }
	 }).end();
};

/* script for sending forms via colorbox */
function SendFormFromColorbox(formUrl, formId) {
	$.ajax({
		url: formUrl,
		global: false,
		type: "POST",
		data: ($(formId).serialize()),
		dataType: "html",
		success: function(msg){
			$("#cboxLoadedContent").html(msg);
			var padding = 10;
			if(msg.indexOf("freecap") > -1) padding += 100;
			var x = $('#cboxLoadedContent #cboxForm').height() + $('#cboxLoadedContent h1').height() + padding;
			$.colorbox.resize({innerHeight:x});
		}
	});
	return false;
}