﻿var ResourceHandlerLocation = "";
var thumbnailPlaceHolders;
var mainArticlePlaceHolders;
var thumbnailImages;
var url;

var timerIndex = 1;
var featuredArticlesCount;
var featuredArticlesIdList;
var timerSeconds;

var timerRunning = false;
var timerID = null;
var mainArticleRank;

var voteAccepted = null;
var voteNotAccepted = null;

function Query( method, url, data ){
	try{
		xmlhttp = new XMLHttpRequest();
	}
	catch (e){ 	xmlhttp = null	}
	if ( xmlhttp == null ){
		try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){ 	xmlhttp = null	}
	}
	if ( xmlhttp == null ){
		try{
		 	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e){ 	xmlhttp = null	}
	}
	if ( xmlhttp == null){
		alert('Your browser not support');
		return;
	}
	xmlhttp.open( method, url,false);
	xmlhttp.send(data);
	return xmlhttp.responseXML;
}


/*Featured articles tab*/

function initializeFeaturedArticles(seconds)
{  

}

function initializeTimer(seconds)
{  
    stopTimer();
    timerSeconds = seconds;
    timerID = setTimeout("rotateFeaturedArticle()", timerSeconds*1000);
    timerRunning = true;
}

function stopTimer() 
{  
    if (timerRunning)               
        clearTimeout(timerID)   
    timerRunning = false
}

window.onunload = function()
{
    stopTimer();
};
function showTab(trig, tabs, items, cssClass){

    for(var i = 0; i< tabs.length; i++){
        var item = document.getElementById(items[i])
        var tab = document.getElementsByName(tabs[i])[0]
        
        if(tab == trig) {
            tab.className = "here";
            item.style.display = 'block';
        }
        else  
        {
            if (i == tabs.length-1)
            {
                tab.className = 'lastLi';
            }
            else
            {
                tab.className = "";
            }
            item.style.display = 'none';
        }
    }
}

// -----------------------------/ TEMP FIX BECAUSE OF BAD WCF USAGE \----------------------------- //
function FIX_A_BUG(x)
{
    for(var i = 0; i < x.length; i++) {
        x[i] = x[i].replace('ArticleTabsCtrl1','');
    }
}
// -----------------------------\ TEMP FIX BECAUSE OF BAD WCF USAGE /----------------------------- //


function showFeaturedArticleTab(trig, articleId,seconds,NextImageNum)
{
    var change = 1;
    
    if (seconds != null)
    {   // Only if image clicked [not if auto rotate (internal javascript call) ]
        initializeTimer(seconds);   // reset timer
        timerIndex = NextImageNum; 
    }

    // -----------------------------/ TEMP FIX BECAUSE OF BAD WCF USAGE \----------------------------- //
    if (document.getElementById(thumbnailImages[0]) == null) { FIX_A_BUG(thumbnailImages); }
    if (document.getElementById(thumbnailPlaceHolders[0]) == null) { FIX_A_BUG(thumbnailPlaceHolders); }
    if (document.getElementById(mainArticlePlaceHolders[0]) == null) { FIX_A_BUG(mainArticlePlaceHolders); }
    // -----------------------------\ TEMP FIX BECAUSE OF BAD WCF USAGE /----------------------------- //

    //small here
    for(var i = 0; i< thumbnailImages.length; i++)
    {
        var item = document.getElementById(thumbnailImages[i]);
        var itemHolder = document.getElementById(thumbnailPlaceHolders[i]);

        if( trig!=null && ( (item == trig) || (itemHolder == trig))) {
            if (item.src == "../newDesignImages/spacer.gif")
            {
                change = 0;
            }
            else
            {
                itemHolder.className = "small here";
            }
        }
        else if (itemHolder!=null) {
            itemHolder.className = "small";
        }
    }
    
    if (change == 1)    
    {  
        fade_out(mainArticlePlaceHolders[0], this, articleId);
    	stop_timeout(mainArticlePlaceHolders[0]);	
    }
}


function rotateFeaturedArticle()
{
    var j=0;      
    showFeaturedArticleTab(document.getElementById(thumbnailPlaceHolders[timerIndex]), featuredArticlesIdList[timerIndex],null,null);
      
    timerIndex += 1;
    if (featuredArticlesCount <= timerIndex)
        timerIndex = 0;

    timerID = setTimeout("rotateFeaturedArticle()", timerSeconds*1000); 
}

function setFeaturedArticlDisplayInfo(id)
{

	var article = FeaturedArticle.getArticleById(id);
	if (article!=null && document.getElementById(mainArticlePlaceHolders[1])!=null)
	{		     
		document.getElementById(mainArticlePlaceHolders[1]).innerHTML = article.title;    
		document.getElementById(mainArticlePlaceHolders[1]).href = article.url;
		document.getElementById(mainArticlePlaceHolders[2]).innerHTML = article.author;
		document.getElementById(mainArticlePlaceHolders[2]).href = article.authorUrl;							
		document.getElementById(mainArticlePlaceHolders[3]).innerHTML = article.date;
		document.getElementById(mainArticlePlaceHolders[6]).innerHTML = article.comentsNumber;
		document.getElementById(mainArticlePlaceHolders[4]).innerHTML = article.rankPlus;
		document.getElementById(mainArticlePlaceHolders[5]).innerHTML = article.rankMinus; 
		document.getElementById(mainArticlePlaceHolders[6]).href = article.url + "#articleComments";                
		document.getElementById(mainArticlePlaceHolders[7]).href = article.url;
		
        if(navigator.userAgent.search(/msie/i)!= -1) //If IE
        {
            document.getElementById(mainArticlePlaceHolders[8]).setAttribute("onclick", new Function (" window.location.href='" + article.url + "';"));
            
            
            document.getElementById(mainArticlePlaceHolders[4]).setAttribute("onclick", new Function (" eval(\"" + article.onclickPlus + "\");"));
		    document.getElementById(mainArticlePlaceHolders[5]).setAttribute("onclick", new Function (" eval(\"" + article.onclickMinus + "\");"));            
        }
        else //If not IE
        {
            document.getElementById(mainArticlePlaceHolders[8]).setAttribute("onclick", " window.location.href='" + article.url + "';");
            
            document.getElementById(mainArticlePlaceHolders[4]).setAttribute("onclick", " eval(\"" + article.onclickPlus + "\");");
		    document.getElementById(mainArticlePlaceHolders[5]).setAttribute("onclick", " eval(\"" + article.onclickMinus + "\");");
        }

		ch_img_bg(document.getElementById(mainArticlePlaceHolders[0]), article.bigImageSrc);
	} 
}

function ratingVotedAfter(idButBox, idMesBox, dspl)
{
	document.getElementById(idMesBox).style.display = 'none';
	document.getElementById(idButBox).style.display = dspl;
}

function ratingVoted(idMesBox, idMesBox2, idButBox, caption)
{
	var dspl = document.getElementById(idButBox).style.display;
	document.getElementById(idMesBox2).innerHTML = caption;
	document.getElementById(idButBox).style.display = 'none';
	document.getElementById(idMesBox).style.display = dspl;
	setTimeout('ratingVotedAfter(\''+idButBox+'\',\''+idMesBox+'\',\''+dspl+'\');', 5000);
}

/* Rating*/
function setRating(id, ratingType, rank, cntx, positiveHolderId, negativeHolderId, butId, mesId, mes2Id, accepted, notAccepted)
{
	var positiveHolder = document.getElementById(positiveHolderId);
	var negativeHolder = document.getElementById(negativeHolderId);
	
	var req = Query('GET', cntx + "Rank.ashx?rand=" + Math.random() + "&ratingType=" + ratingType + "&id="  + id + "&rank=" + rank, null);
	if (req != null)
	{
		var response = req.documentElement;
		if ( (response != null) && (response.getElementsByTagName("rating").length > 0) )
		{
		    var responseRatePlus = response.getElementsByTagName("rating")[0].getElementsByTagName("plus")[0].childNodes[0].nodeValue;
		    var responseRateMinus = response.getElementsByTagName("rating")[0].getElementsByTagName("minus")[0].childNodes[0].nodeValue;
			positiveHolder.innerHTML = responseRatePlus;
			negativeHolder.innerHTML = responseRateMinus;
			voteAccepted = (voteAccepted!=null) ? voteAccepted : accepted;
			ratingVoted(mesId, mes2Id, butId, voteAccepted);

            //Update FeaturedArticles JSON object, if rating from the Featured Articles rotator
			if (FeaturedArticle != null && FeaturedArticle.getArticleById != null) 
			{
			    var article = FeaturedArticle.getArticleById(id);
			    if (article != null) 
			    {
			        article.rankPlus = responseRatePlus;
			        article.rankMinus = responseRateMinus;
			    }
			}}
		else
		{
			voteNotAccepted = (voteNotAccepted!=null) ? voteNotAccepted : notAccepted;
			ratingVoted(mesId, mes2Id, butId, voteNotAccepted);
		}
	}
}

/*profile info*/
function ClearElements(elements, index)
{

      for(var i = index; i< elements.length; i++)
      {
            document.getElementById(elements[i]).value ="";
      }
}


function getLeaguesBySport(id) {

       var id = document.getElementById(id).value;

       var req = Query('GET', ResourceHandlerLocation + 'ResourceHandler.ashx?rand=' + Math.random() + '&task=leagues' + '&identity=' + id , null);
       ResourceHandlerLocation = "";
 
        var response = req.documentElement;

                       
       if(response != null)
       {     
            this._listIems = new Array(); 
    
            for(index = 0; index < response.getElementsByTagName('league').length; index++)
            {
                this._listIems[index] = response.getElementsByTagName('league')[index].lastChild.childNodes[0].nodeValue;
            }
       }

    
       return  this._listIems;
}

function getTeamsByLeague(id) {

       var id = document.getElementById(id).value;
       
       var req = Query('GET', ResourceHandlerLocation + 'ResourceHandler.ashx?rand=' + Math.random() + '&task=teams' + '&identity=' + id , null);
       ResourceHandlerLocation = "";  
         
       var response = req.documentElement;
      
       if(response != null)
       {     
            this._listIems = new Array();    
              
            for(index = 0; index < response.getElementsByTagName('team').length; index++)
            {
                 this._listIems[index] = response.getElementsByTagName('team')[index].lastChild.childNodes[0].nodeValue;    
             }
      }
      
        return  this._listIems;
 
}

function getPlayersByTeam(id) {

      var id = document.getElementById(id).value;
      
       var req = Query('GET', ResourceHandlerLocation + 'ResourceHandler.ashx?rand=' + Math.random() + '&task=players' + '&identity=' + id , null);
       ResourceHandlerLocation = "";
         
       var response = req.documentElement;
     
       if(response != null)
       {
            this._listIems = new Array();    
                    
            for(index = 0; index < response.getElementsByTagName('player').length; index++)
            {
                  this._listIems[index] = response.getElementsByTagName('player')[index].lastChild.childNodes[0].nodeValue;
               
             }
      }
      
        return  this._listIems;
}


/* Fade in/ fade out*/


var timers=new Array();

function _fade_in(element, opacity) // private
    {
    // Get object
    obj = document.getElementById(element);

    // Tidy up timer and register
    stop_timeout(element);

    // Make visible
//    if (opacity==0)
//        obj.style.visibility="";
 
    // Fade in one more step
    if (opacity <= 100) {
        _set_opacity(obj, opacity);
        opacity+=20;
        window.setTimeout("_fade_in(\'"+element+"\',"+opacity+")", 20);//50
        }

    // If fully visible, start countdown to fade out
    if (opacity >= 100) {
 
        //window.setTimeout("_fade_out(\'"+element+"\', 100)", 5000);
        }
    }

function _fade_out(element, opacity, articleId) // private 
{
    if ( document.getElementById(mainArticlePlaceHolders[1])!=null)
    {
    // Get object
    obj = document.getElementById(element);

    // If still visible, fade down one further step
    if (opacity > 0) {
        _set_opacity(obj, opacity);
        opacity-=20;
        window.setTimeout("_fade_out(\'"+element+"\',"+opacity+","+articleId+")", 20);//50
        }

    // If close to invisible, hide object completely
    if (opacity<10) {

        setFeaturedArticlDisplayInfo(articleId);    
        window.setTimeout("_fade_in(\'"+element+"\',"+opacity+")", 20);//50
        }
    }
}
function _set_opacity(obj, opacity) // private
    {
    opacity=(opacity==100) ? 99.999 : opacity;
    if (obj!=null)
    {
        // IE/Win
        obj.style.filter="alpha(opacity:"+opacity+")";

        // Safari<1.2, Konqueror
        obj.style.KHTMLOpacity=opacity/100;

        // Older Mozilla and Firefox
        obj.style.MozOpacity=opacity/100;

        // Safari 1.2, newer Firefox and Mozilla, CSS3
        obj.style.opacity=opacity/100;
    }
}
    
function fade_in(element) // public
    {
    var obj=document.getElementById(element);
    // Start timer
    timers[element]=setTimeout("_fade_in(\'"+element+"\', 0)", 100);
    }

function fade_out(element, e, articleId) // public
    {
    // Tidy up timer and register
    stop_timeout(element);

//    // Make sure we´re outside the whole fading div
//    var relTarg;
//    if (e.relatedTarget) 
//        relTarg = e.relatedTarget;
//    else if (e.toElement) 
//        relTarg = e.toElement;

//    // If all the way out, fade out
//    if (relTarg.id=="") 
        _fade_out(element, 100, articleId);
    }

function stop_timeout(element) // public
    {
    // Stop timer
    clearTimeout(timers[element]);

    // Clear register
    timers[element]=false;
    }

