﻿function getAjax()
{
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Sorry, this function is possible only for Ajax enabled Browsers.");
      return false;
      }
    }
  }
  return xmlHttp;
}

function PostVote(vote, currentSite, newSite, position, parentID) {
    var params = "vote=" + vote + "&current=" + escape(currentSite) + "&site=" + escape(newSite) + "&pos=" + position;
    var xmlHttp = getAjax();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (vote == 0) {
                try { _gaq.push(['_trackEvent','Votes', 'Down', newSite]); } catch (e) { }
                document.getElementById(parentID).innerHTML = '<div title="Not Similar" class="t-d-s">&nbsp;</div><span style="float:left;display:block;padding-left:5px;line-height:22px;"> Thanks for voting</span>';
            }
            else {
                try { _gaq.push(['_trackEvent','Votes', 'Up', newSite]); } catch (e) { }
                document.getElementById(parentID).innerHTML = '<div title="Similar" class="t-u-s">&nbsp;</div><span style="float:left;display:block;padding-left:5px;line-height:22px;"> Thanks for voting</span>';
            }
        }
    }

    xmlHttp.open("POST", "/vote", true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.send(params);
}

function Vote(link, index,site)
{
    var xmlHttp = getAjax();
    xmlHttp.onreadystatechange=function()
    {
        if(xmlHttp.readyState==4)
        {
            if(link.substring(0,10) == "/thumbdown") {
                try { _gaq.push(['_trackEvent', 'Votes', 'Down', site]); } catch (e) { }
                document.getElementById("ResultButtons" + index).innerHTML = '<div title="Not Similar" class="t-d-s">&nbsp;</div><span style="float:left;display:block;padding-left:5px;line-height:22px;"> Thanks for voting</span>';
            }
            else {
                try { _gaq.push(['_trackEvent', 'Votes', 'Up', site]); } catch (e) { }
                document.getElementById("ResultButtons" + index).innerHTML = '<div title="Similar" class="t-u-s">&nbsp;</div><span style="float:left;display:block;padding-left:5px;line-height:22px;"> Thanks for voting</span>';
            }
        }
    }
    xmlHttp.open("GET",link+"?pos="+index,true);
    xmlHttp.send(null);
}

function SuggestNewSite(siteInput , captchaInput , captchaImg , errMsgElement , successMsgElement  )
{
    var xmlHttp = getAjax();
    var params = "newSite=" + document.getElementById(siteInput).value + "&newSiteCaptcha=" + document.getElementById(captchaInput).value;

    xmlHttp.onreadystatechange=function()
    {
        if(xmlHttp.readyState==4)
        {
            if (xmlHttp.status == 200)
            {
                FinishSuggest(siteInput , captchaInput , captchaImg , errMsgElement , successMsgElement );
            } else if (xmlHttp.status == 401)
            {
                WrongCaptcha(captchaInput,errMsgElement,captchaImg);
            }
        }
    }
    
    xmlHttp.open("POST","/suggest",true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    
    xmlHttp.send(params);
}

function RefreshCaptcha(captchaImg)
{
    var s=document.getElementById(captchaImg).src;
    var temp = new Array();
    temp = s.split('/');
    var index = temp[temp.length-2];
    var num = parseInt(index);
    num=num+1;
    document.getElementById(captchaImg).src = "/images/" + num + "/captcha.gif";
}

function WrongCaptcha(captchaInput,errMsgElement,captchaImg)
{
    RefreshCaptcha(captchaImg);
    document.getElementById(captchaInput).value = "";
    
    document.getElementById(captchaInput).style.border = "1px solid red";
    document.getElementById(errMsgElement).style.display = "block";
}

function FinishSuggest(siteInput, captchaInput, captchaImg, errMsgElement, successMsgElement) 
{
    try {
        var suggestedSite = document.getElementById(siteInput).value;
        var suggestPlace = 'BottomSuggest';

        if (siteInput == 'newSiteRP') {
            suggestPlace = 'SideSuggest';
        }

        _gaq.push(['_trackEvent', 'Suggest', suggestPlace, suggestedSite]); 
    } catch (e) { }
    
    document.getElementById(successMsgElement).style.display = "inline";
    setTimeout("NewSuggest('"+siteInput +"','"+ captchaInput +"','"+ captchaImg +"','"+ errMsgElement+"','"+successMsgElement+"')",3000);
}

function NewSuggest(siteInput , captchaInput , captchaImg , errMsgElement , successMsgElement)
{
    document.getElementById(successMsgElement).style.display = "none";
    RefreshCaptcha(captchaImg);
    document.getElementById(captchaInput).style.border = "1px solid #B1BBC7";
    document.getElementById(errMsgElement).style.display = "none";
    document.getElementById(captchaInput).value = "";
    document.getElementById(siteInput).value = "";
    $("#SuggestSiteBox").hide(200);
}

function ShowSearchProviderNote()
{
 if (window.external && ("AddSearchProvider" in window.external)) {
    if (!Get_Cookie('SearchProviderNote'))
    {
        document.getElementById("SearchProviderNote").style.display = "block";
    }
 }
}

function AddSearchProvider()
{
 if (window.external && ("AddSearchProvider" in window.external)) {
   // Firefox 2 and IE 7, OpenSearch
   window.external.AddSearchProvider("http://www.similarsites.com/SimilarSitesSearchProvider.xml");
 } else {
   // No search engine support (IE 6, Opera, etc).
   alert("No search engine support");
 }
    DontShowNote();
}

function DontShowNote()
{
    document.getElementById("SearchProviderNote").style.display = "none";
    
    Set_Cookie( 'SearchProviderNote', 'removed', 365, '/', '', '' );
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
	
// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function HPQuickSearchInit()
{
    var changeBox = document.getElementById('PS');
    if (changeBox != null)
    {
        var myItems = changeBox.getElementsByTagName('li');

        for (var i=0;i<myItems.length;i++) 
        {
	        myItems[i].onmouseover = function(){this.className = 'siteWrapper siteWrapperHover';};
	        myItems[i].onmouseout = function(){this.className = 'siteWrapper';};
        }
    }            
}

function VoteChangeInit()
{
    var changeBox = document.getElementById('VoteChangeBox');

    if (changeBox != null)
    {
        var myItems = changeBox.getElementsByTagName('li');

        for (var i=0;i<myItems.length;i++) 
        {
            if (myItems[i].id != 'VoteChangeTitle')
            {
	            myItems[i].onmouseover = VoteItem_MouseOver;
	            myItems[i].onmouseout = VoteItem_MouseOut;
            }
        }
    }
}
function VoteItem_MouseOver()
{
    this.className = 'VoteItem VoteItemHover';
}

function VoteItem_MouseOut()
{
    this.className = 'VoteItem';
}

function AddFloatingDownload()
{
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
    document.write("<a title=\"SimilarWeb for Firefox\" rel=\"nofollow\" onclick=\"javascript:_gaq.push(['_trackPageview', '/Download/SimilarWebFF2.xpi?src=external-similarsites-corner']);\"  href=\"http://similarsitesppi2.ourtoolbar.com/xpi?confirmed&amp;src=external-similarsites-footer\"><img style=\"position: fixed; bottom: 0; right: 0;\" alt=\"SimilarWeb for Firefox\" title=\"SimilarWeb for Firefox\" src=\"/images/dl-sw.png\" /></a>");
}
else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=7) {
        document.write("<a title=\"SimilarWeb for Internet Explorer\" rel=\"nofollow\" onclick=\"javascript:_gaq.push(['_trackPageview','/Download/SimilarWebIE.exe?src=external-similarsites-corner']);\"  href=\"/Download/SimilarWebIE.exe\"><img style=\"position: fixed; bottom: 0; right: 2px;\" alt=\"SimilarWeb for Internet Explorer\" title=\"SimilarWeb for Internet Explorer\" src=\"/images/dl-sw-ie.png\" /></a>");
    }
}
else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
        document.write("<a title=\"SimilarWeb for Chrome\" rel=\"nofollow\" onclick=\"javascript:_gaq.push(['_trackPageview','/Download/SimilarWebCM.cm?src=external-similarsites-corner']);\"  href=\"/Download/SimilarWebCM.cm\"><img style=\"position: fixed; bottom: 0; right: 2px;\" alt=\"SimilarWeb for Chrome\" title=\"SimilarWeb for Chrome\" src=\"/images/DownloadPromo_Sticky2_CH.png\" /></a>");
}
}


function showAddSite()
{
     var tab = $(".tab.tabSelected");
     
     if(tab.length > 0)
     {
        if(tab.attr("id") == "tabReviews")
        {
            tabClick(document.getElementById("tabSimilarsites"));
        }
     }
     
    if(document.getElementById('SuggestSiteBox').style.display == "none")
    {
        $("#SuggestSiteBox").show(200);
    }
    else
    {
        $("#SuggestSiteBox").hide(200);
    }    
}

function tabClick(element)
{
    if(element.className == 'tab tabSelected')
        return;
        
    $(".tab.tabSelected").removeClass('tabSelected');
    element.className = 'tab tabSelected'; 
    
    switch(element.id)
    {
        case "tabReviews":
        
            document.getElementById("SimilarSitesContent").style.display = "none";
            //document.getElementById("ReviewsContent").style.display = "block";  
            $("#ReviewsContent").fadeIn("fast");
            if($("#disqus").length == 0)
            {
                var script = "<div id='disqus'>" +                                                                             
                             "<script type='text/javascript'>"+
                             "var disqus_shortname = 'similarsites';"+
                             "(function () {"+
                             "var s = document.createElement('script'); s.async = true;"+
                             "s.src = 'http://disqus.com/forums/similarsites/count.js';"+
                             "(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);"+
                             "}());"+
                             "</script>"+
                             "</div>";
                $("body").append(script);
                
            }
        break;
        case "tabSimilarsites":
        
            document.getElementById("ReviewsContent").style.display = "none"; 
            $("#SimilarSitesContent").fadeIn("fast");
            
        break;
        default:
        break;
    }
}
