/*
  main.js - SAPO Desport Javascript file
 */

/*
 Variables
 */

var
	textSize = 1.1,
	mrecTag = null,
	tab_list = [];

/*
  Pesquisa: muda entre thumbs e tamanho normal...
 */

function switchThumbBigPhoto(evt) {
    var targeted = evt.target;
    var ct = targeted.down('a');
    if (!ct) ct = targeted.up('a');

    var image_url = ct.href;
    if (ct.down('.list-img-media-big')) window.location = image_url;

    if ( $('ul_list_images').down('.list-img-media-big') ) {
        var imgsrc = $('ul_list_images').select('.list-img-media-big')[0].src;
        var patt = /(.+&h=).+$/i;
        var re = new RegExp(patt);
        var m = re.exec(imgsrc);

        var th_div = new Element( 'div', { 'class': 'list-img-media-ct' } );
        th_div.appendChild( new Element('img', { 'class': 'list-img-media', 'alt': '', 'src': m[1] + '75&W=100' } ) );

        $('ul_list_images').select('.list-img-media-ct-big')[0].up().replaceChild(th_div, $('ul_list_images').select('.list-img-media-ct-big')[0]);
    }

    var th_div_small = new Element('div', {'class':'list-img-media-ct-big'});
    var thumb_img_small = new Element('img', {'class':'list-img-media-big', 'src':'http://thumbs.sapo.pt/?pic='+ct.href+'/&H=396&W=600',  'alt':''});
    th_div_small.appendChild(thumb_img_small);
    ct.replaceChild(th_div_small,ct.firstDescendant());

}

/*
  Share
 */

function sendtofriend ( uri ) {

    if (window.XMLHttpRequest)
        ajax = new XMLHttpRequest();
    else
        ajax = new ActiveXObject("Microsoft.XMLHTTP");

    if (ajax) {
        data = 'uri=' + escape( uri );
        ajax.open('POST', 'http://desporto.sapo.pt/services/sendtofriend.json', true);
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        ajax.setRequestHeader('Content-Length', data.len);
        ajax.send(data);
    }
}

/*
  Article font size +/-
 */

function biggerText ( ) {

	textSize += 0.1;
	applyTextSize();
	saveTextSize();

	return false;

}

function lowerText ( ) {

	textSize -= 0.1;
	applyTextSize();
	saveTextSize();

	return false;

}

function applyTextSize ( ) {

	$$(".article-intro")[0].style.fontSize = textSize+"em";
	$$(".article-txt")[0].style.fontSize = textSize+"em";

}

function loadTextSize ( ) {

	var
		size = parseFloat(getCookie("textSize"));

	if ( !size ) return;
	textSize = size;
	applyTextSize();

}

function saveTextSize ( ) {

	setCookie("textSize",textSize.toFixed(2),10);

}



/*
  Util functions
 */


// Dinamically JS loading

function LoadJS(urls,onload) {
	var hits = 0, errors = 0, scr;

	if ( typeof urls == "string" )
		urls = [ urls ];
	for ( var x = 0 ; x < urls.length ; x++ ) {
		scr = document.createElement("SCRIPT");
		scr.type = "text/javascript";
		scr.onreadystatechange = function() {
			if ( this.readyState == 'complete' || this.readyState == 'loaded' )
				if(++hits == urls.length) onload(errors);
		}
		scr.onerror = function() {
			if(++hits == urls.length) { errors++; onload(errors); }
		};
		scr.onload = function() {
			if(++hits == urls.length) onload(errors);
		};
		scr.src = urls[x];
		document.body.appendChild(scr);
	}
}


// Cookies

function getCookie(name) {

	var
		allCookie = ""+document.cookie,
		ind = allCookie.indexOf(name),
		ind1;

	if (ind == -1 || name == "")
		 return null;

	ind1 = allCookie.indexOf(';',ind);
	if (ind1 == -1)
		ind1 = allCookie.length; 

	return unescape(allCookie.substring(ind+name.length+1,ind1));

}

function setCookie(name,value,days) {

	var
		today = new Date(),
		expire = new Date();

	if ( days == null || days == 0)
		days = 1;

	expire.setTime(today.getTime() + 3600000*24*days);
	document.cookie = name+"="+ escape(value) + ";expires="+expire.toGMTString();
}



/*
  Simulate a site interaction
 */
/*
function siteInteraction ( affiliate ) {

	var
		mrec;


	// Identify MREC

	if ( ((mrec = document.getElementById('mrec')) == null) && ((mrec = document.getElementById('pub300x250')) == null) )
		return true;
	if ( mrec.nodeName.toLowerCase() == 'div' )
		mrec = (mrec.getElementsByTagName("IFRAME"))[0];

	// Refresh MREC

	if ( mrec ) {
		if ( mrecTag == null ) mrecTag = mrec.src;
		mrec.src = mrecTag;
	}

	// Hit Netscope

	if ( typeof(w_counter) != 'undefined' )
		w_counter.count();
	if ( typeof(nsAccounts) != 'undefined' ) {
		for ( var x = 0 ; x < nsAccounts.length ; x++ ) {
			if ( nsAccounts[x].obj ) nsAccounts[x].obj.count();
		}
	}

	return true;

}
*/

function siteInteraction ( affiliate ) {

	var
		mrec;

	hitNetscope();
	
	
	
	// Identify MREC

	if ( ((mrec = document.getElementById('mrec')) == null) && ((mrec = document.getElementById('pub300x250')) == null) )
		return true;

/*
	if ( mrec.nodeName.toLowerCase() == 'div' )
		mrec = (mrec.getElementsByTagName("IFRAME"))[0];

	// Refresh MREC

	if ( mrec ) {
		if ( mrecTag == null ) mrecTag = mrec.src;
		mrec.src = mrecTag;
	}
*/

	var div = document.getElementById('pub300x250');
	if(div) {
		var iframe;
		if ( div.nodeName.toLowerCase() == 'div' ) {
			iframe = (div.getElementsByTagName("IFRAME"))[0];
		}
		if(iframe) {
			if ( mrecTag == null ) mrecTag = iframe.src;
			iframe.src = mrecTag;
		} else {
			if(typeof pub_zoneid !== 'undefined') {
			var iframe_code = '<iframe width="300" height="250" scrolling="no" frameborder="0" src="http://estadiovirtual.sapo.pt/pub/zoneid/'+pub_zoneid+'?referrer='+escape(document.referrer)+'" id="iframe_mrec"></iframe>';
			div.innerHTML = iframe_code;
			}
		}
	}


	return true;

}

function hitNetscope() {
	// Hit Netscope
	if (typeof wreport_ok != "undefined") {
		if(wreport_ok==1){ var w_counter = new wreport_counter(WRP_SECTION, WRP_SUBSECTION, WRP_ID, WRP_ACC, WRP_CHANNEL, WRP_SECTION_GRP, WRP_SUBSECTION_GRP);
			w_counter.add_content(WRP_CONTENT);
			w_counter.count();
		}
	}
}


/*
  Tabs
*/

function TabAdd(id) { tab_list.push(id); }
function TabsShow() { for(var x = 0; x < tab_list.length ; x++) new Fabtabs(tab_list[x]); }


/*
  Functions to handle page auto reloading on change
 */

function startTicker(time,id) {
    setInterval( "doTick("+time+","+id+")", 60000 );
}

function doTick(time,id) {
    var url = 'http://desporto.sapo.pt/services/c.html?key='+id;

    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(transport) {
            var last_update = transport.responseText.evalJSON() || 0;
            if (last_update > time)
				window.location.reload();
        }
    });
}


/*
  Fixed layer
 */

function ShowPubFixedLayer(content) {
        LoadJS("http://js.staging.sapo.pt/Bundles/FixedLayer.js",function(errs){
                var layer = new SAPO.Component.FixedLayer({
                        contentCallback: function() { return '<div id="fl_pub_place" style="overflow:hidden;width:328px;height:80px">'+content+'</div><span>PUB</span>' },
                        width: 328,
                        height: 90,
                        /* showAfterPosition: 50, */
			special: 'desporto',
			specialOpts: { element: s$('share_elem_id') },
                        keepClosed: true
                });
        });                                     
}



/*
  Events
 */


// On load

function onLoad ( ) {

	loadTextSize();

}

function onDOMend ( ) {

	TabsShow();

}


// Register page load event

if (Event) Event.observe(window,"load",onLoad);


/*
  Load other useful scripts
 */

document.write("<script language=\"JavaScript\" type=\"text/javascript\" src=\"http://imgs.sapo.pt/js/DESPORTO/1.0.4/sapotabs.js\"></script>");
document.write("<script language=\"JavaScript\" type=\"text/javascript\" src=\"http://imgs.sapo.pt/js/DESPORTO/1.0.4/elements.js\"></script>");
document.write("<script language=\"JavaScript\" type=\"text/javascript\" src=\"http://imgs.sapo.pt/js/DESPORTO/1.0.4/polls.js\"></script>");

