﻿function tvgDisplayRemoteAdvert(remoteUrl, id)
{
document.getElementById(id).innerHTML = '';
if (window["tvgProxyUrl"] == undefined)
    {
    tvgProxyUrl = "http://proxy.tvgenius.co.uk/";
    }
var url = tvgProxyUrl + "adProxy.aspx?remoteURL=" + encodeURIComponent(remoteUrl) + "&id=" + id + "&important=" + Math.round(Math.random() * 10000000000).toString() ;
    tvgAddJavascript(url);
    tvgLog(url);
}


function tvgLog(s)
{
    try
	    {
	    //console.log(s);
	    }
	    catch(e){}
}


function tvgNibbleHtmlFragment(html,el)
{
//tvgLog("Nibbling " + html);

//execute any scripts
html = tvgExecuteScripts(html, el);

//get the name of the first element...
var firstEl = /<([^\s\>>]*)/.exec(html);
if (firstEl != null)
    {
    firstEl = firstEl[1];

    //look for a matching closing position...
    var regClosing = new RegExp("<\/"+firstEl +"[^\>]*>", "ig");
    var regOpening = new RegExp("<"+firstEl +"[^\>]*>", "ig");
    var numberOpen = 0;
    var currentPosition = 0;

    var nextOpening = regOpening.exec(html, currentPosition);
    var nextClosing = regClosing.exec(html, currentPosition);

    while (currentPosition < html.length)
        {
        var nextOpeningIndex;
        var nextClosingIndex;
        if (nextOpening != null)
            {
            nextOpeningIndex = nextOpening.index;
            }
        else
            {
            nextOpeningIndex = html.length;
            }
            
        if (nextClosing != null)
            {
            nextClosingIndex = nextClosing.index;
            }
        else
            {
            nextClosingIndex = html.length;
            }    
        
        if (nextOpeningIndex < nextClosingIndex)
            {
            currentPosition = nextOpening.index + nextOpening[0].length;
            if (html.substr(currentPosition-3, 2) != "/>")
                {
                numberOpen += 1;
                }
            nextOpening = regOpening.exec(html);
            }
            
         if (nextOpeningIndex > nextClosingIndex)
            {
            currentPosition = nextClosing.index + nextClosing[0].length;
            numberOpen -= 1;
            nextClosing = regClosing.exec(html);
            }
            
         if (nextOpeningIndex == nextClosingIndex)
            {
            currentPosition = html.length;
            break;
            }
            
         if (numberOpen == 0)
            {
            //we have valid HTML fragment...
            el.innerHTML+= html.substring(0,currentPosition);
            tvgLog("adding " + html.substring(0,currentPosition));
            return tvgNibbleHtmlFragment(html.substr(currentPosition),el);
            }           
        }
    }
    
//no valid HTML fragment
return html;
}

function tvgExecuteScripts(html, el)
{
//run the scripts...
var i = -1;
var n = 0;
var list = new Array();
var jshtml = html.replace(/<iframe[^>]*>.*?<\/iframe>/gi, "");
jshtml = html.replace(/<iframe[^>]*>.*/gi, "");
jshtml = jshtml.replace(/<noscript[^>]*>.*?<\/noscript>/gi, "");


var regex = /<script[^>]*src=["']*([^"']*)[^>]*>[\S\s]*?<\/script[^>]*>|<script[^>]*vbscript[^>]*>([\S\s]*?)<\/script[^>]*>|<script[^>]*>([\S\s]*?)<\/script[^>]*>/gi;
var m = regex.exec(jshtml);

//tvgLog("parsing " + jshtml);

while (m != null)
    {
    list[n] = new Object;
    //tvgLog(m.index);
    //tvgLog(m[0].length);
    
    if (i +1 < m.index -1)
    {
        list[n].html = jshtml.substr(i+1, m.index);
    }

    if (m[1] !== undefined)
        {
        list[n].src = m[1].replace('&amp;', '&');
        }
    if (m[3] !== undefined)
        {
        list[n].js= m[3];
        }
    if (m[2] !== undefined)
        {
        list[n].vbs= m[2];
        }
    n++;
    i = m.index + m[0].length;            
    m = regex.exec(jshtml,i);
    }
    
for (i = 0; i < list.length; i++)
{
    if (list[i].src !== undefined && list[i].src != '')
    {
            tvgLog ("loading " + list[i].src );
            tvgDisplayRemoteAdvert(list[i].src , getId(el));
    }
    else
    {        
        if (list[i].js !== undefined && list[i].js != '')
        {
                tvgLog ("running js " + list[i].js);
                tvgAddScript("var tvgTemp = '';document.close=function() {if (tvgTemp!=''){document.getElementById('" + getId(el) + "').innerHTML+=tvgTemp;tvgTemp='';}};document.writeln = function (s) {tvgTemp = tvgNibbleHtmlFragment(tvgTemp + s + '\\r\\n',document.getElementById('" + getId(el) + "'));};document.write = function (s) {tvgTemp=tvgNibbleHtmlFragment(tvgTemp +s,document.getElementById('" +  getId(el) + "'));};\r\n" + list[i].js + "\r\ndocument.close();\r\n", "text/javascript");
        }
        else
        {
            if (list[i].js !== undefined && list[i].vbs != '')
            {
                tvgLog ("running vbs " + list[i].vbs);
                tvgAddScript ( list[i].vbs, "text/vbscript");
            }

        }
    }
    
}

return html.replace(regex,'');  

}


function getId(el)
{
if (el.id == "")
{
return getId(el.parentNode);
}
else
{
return el.id;
}
}

function tvgAddScript(js, type)
	{
	var script = document.createElement("script");
	script.setAttribute("type", type);
	if (null == script.canHaveChildren || script.canHaveChildren)
	    {
        script.appendChild(document.createTextNode(js));
        }
   else {
        script.text =js;
        
        } 
	document.getElementsByTagName("head")[0].appendChild(script);
	}



function tvgAddJavascript(url)
	{
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", url);	
	document.getElementsByTagName("head")[0].appendChild(script);
	}