<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
	<xsl:output method="html" indent="no" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"/>
    <xsl:include href="namedtemplates.xsl"/>
        
	<xsl:template match="/configuration/iptv/global_settings" mode="iptv">
        var base_ip_addr = &quot;<xsl:value-of select="base_dest_ip_addr" />&quot;;
        var default_ip_port = <xsl:value-of select="default_dest_port" />;
        var default_ip_ttl = <xsl:value-of select="default_opt_ip_ttl" />;
        var default_network_if = &quot;<xsl:value-of select="default_network_if" />&quot;
	</xsl:template>

	<xsl:template match="/configuration/iptv/iptv_destination" mode="iptv">
        iptv_dests.push( new TIptvDestination( &quot;<xsl:value-of select="dest_ip_addr" />&quot;,
        <xsl:value-of select="dest_port" />, &quot;<xsl:value-of select="network_if" />&quot;,
        <xsl:value-of select="opt_ip_ttl" />, <xsl:value-of select="constant_bit_rate" />,
        <xsl:value-of select="pat_rate" />, new Array(
        <xsl:for-each select="programs/program_reference">
	   new TIptvProgramReference(<xsl:value-of select="source_port" />, <xsl:value-of select="source_program_number" />) <xsl:if test="position() != last()">,</xsl:if>
	   </xsl:for-each>
	   ) ) );
	</xsl:template>

    <xsl:template match="/configuration/status/port/available_programs/program" mode="iptv">
        avail_progs.push(new TAvailProgram( <xsl:value-of select="@program_number" />, &quot;<xsl:value-of select="@name" />&quot;, <xsl:value-of select="../../@index" /> ) );
    </xsl:template>

	<xsl:template match="/configuration">
        <html>

        <xsl:call-template name="head"/>

		<body onload="javascript:load(); StartFloat();">
			<xsl:call-template name="initROPage">
				<xsl:with-param name="pageName">iptv.py</xsl:with-param>
				<xsl:with-param name="message" select="$message"/>
			</xsl:call-template>
			<div id="displayresults">
				<div class="row">
					<div class="generalcell" style="font-size:16pt;height:40px;">
						<br/>iptv
					</div>
					<br/>
					<br/>
				</div>
				<div class="row">
					<div class="generalcell" style="width:220px;">
						Current Destinations
					</div>
					<div class="generalcell" style="width:220px;">
						Programs
					</div>
				</div>
				<div class="row">
					<div style="width:450px;">
						<form name="iptv" action="">
							<select NAME="dest" size="15" ONCLICK="showsourceprograms()" style="width:220px;" />
							<select multiple="multiple" NAME="source*" size="15" style="width:220px;"/>
						</form>
					</div>
				</div>
			</div>
		</body>
	</html>
	</xsl:template>
	<xsl:template name="head">
		<head>
			<title>IPTV</title>
			<xsl:call-template name="common_imports"/>
			<script type="text/javascript">
            var delimiter = "^"
        
            function TAvailProgram(pn, name, port)
                {
                this.pn = pn;
                this.name = name;
                this.port = port;
                }
        
            var avail_progs = new Array();  // list of TAvailProgram
        
            function TIptvProgramReference(port, pn)
                {
                this.source_port = port;
                this.source_pn = pn;
                }
        
            function TIptvDestination(addr, port, network_if, ttl, bps, pat_rate, progs)
                {
                this.dest_ip_addr = addr;
                this.dest_ip_port = port;
                this.dest_network_if = network_if;
                this.dest_ip_ttl = ttl;
                this.bps = bps;
                this.pat_rate = pat_rate;
                this.progs = progs;
                }
        
            var iptv_dests = new Array();   // list of TIptvDestination
        
        
            // Ajax section
            function makeRequest(url, parameters) {
                http_request = false;
                if (window.XMLHttpRequest) { // Mozilla, Safari,...
                    http_request = new XMLHttpRequest();
                    if (http_request.overrideMimeType) {
                    // set type accordingly to anticipated content type
                        //http_request.overrideMimeType('text/xml');
                        http_request.overrideMimeType('text/html');
                    }
                } else if (window.ActiveXObject) { // IE
                    try {
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                            http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                    }
                }
                if (!http_request) {
                    alert('Cannot create XMLHTTP instance');
                    return false;
                }
                http_request.onreadystatechange = alertContents;
                http_request.open('GET', url + parameters, true);
                http_request.send(null);
                }
        
            function alertContents() {
                if (http_request.readyState == 4) {
                    if (http_request.status == 200) {
                        //alert(http_request.responseText);
                        result = http_request.responseText;
                        document.getElementById('myspan').innerHTML = result;
                    } else {
                        alert('There was a problem with the request.');
                    }
                }
            }
        
        
            // Update the destinatio with new sources.
            function updatedest(obj) {
            var getstr = "?";
            d = obj.dest.selectedIndex;
            iptv_dests[d].progs=null;
            getstr += obj.dest.name + "=" + obj.dest.options[d].value + "&amp;";
            ar = new Array;
            idx = 0;
            var sel = obj.elements['source*'];
            for (j=0; j &lt; sel.length; j++) {
                if (sel.options[j].selected == true)
                {
                getstr += sel.name + "=" + sel.options[j].value + "&amp;";
                vals = sel.options[j].value.split(delimiter);
                port = vals[0];
                pn = vals[1];
                ar[idx]=new TIptvProgramReference(port, pn);
                idx++;
                }
            }
            iptv_dests[d].progs=ar;
            getstr+="action=apply&amp;function=update";
            makeRequest('/asimux/iptv.py', getstr);
            }
            
            
            // loop through avail programs and output in select form.
            function showavail ()
            {
            for (i = 0; i &lt; avail_progs.length; i++)
                {
                //var elOptNew = document.createElement('option');
                var name = avail_progs[i].name+" ("+avail_progs[i].port+","+avail_progs[i].pn+")";
                var val = avail_progs[i].port+delimiter+avail_progs[i].pn;
                var newOpt1 = new Option(name, val);
                document.iptv.elements['source*'].options[i] = newOpt1;
                //document.write("<option value="+avail_progs[i].port+delimiter+avail_progs[i].pn+">"+avail_progs[i].name+" ("+avail_progs[i].port+","+avail_progs[i].pn+")</option><br/>");
                }
            }
        
        
            //loop through the dstination array and output into form select
            function showdest ()
            {
            document.iptv.dest.options.length=0;      // first clear
            for (i = 0; i &lt; iptv_dests.length; i++)
                {
                name = iptv_dests[i].dest_ip_addr+","+iptv_dests[i].dest_ip_port;
                val = i;
                var newOpt1 = new Option(name, val);
                document.iptv.dest.options[i] = newOpt1;
                //document.write("<option value="+i+">"++"</option><br/>");
                }
                // attempt to highlight the first
                //document.iptv.dest.options[0].selected=true;
                //resetforms();
            }
            
            
            function processit()
            {
            dest = document.iptv.dest.selectedIndex;
            //alert(iptv_dests[dest].dest_ip_addr);
            src = ""
            idx = 0;
            cnt = document.iptv.elements["source*"].length;
            for ( j = 0 ; j &lt; cnt; j++)
            {
            if (document.iptv.elements["source*"].options[j].selected==true)
                {
                if (idx == 0)
                {
                src=document.iptv.elements["source*"].options[j].value;
                }
                else
                {
                src=src+delimiter+document.iptv.elements["source*"].options[j].value;
                }
                idx++;
                }
            }
            alert(dest+ " =" + src);
            //resetforms();
            }
            
            
            // clears the source program list
            function clearselected()
                {
                cnt = document.iptv.elements["source*"].length;
                //cnt = document.iptv.source.length;
                for ( j = 0 ; j &lt; cnt; j++)
                {
                document.iptv.elements["source*"].options[j].selected=false;
                }
                }
            
            
            
            // get the soruce names from the
            function showsources ()
            {
            dest = document.iptv.dest.selectedIndex;
            if (iptv_dests[dest].progs != null)
                {
                //alert(iptv_dests[dest].progs.length);
                for ( j = 0 ; j &lt; iptv_dests[dest].progs.length; j++)
                    {
                    idx = findsource(iptv_dests[dest].progs[j].source_port,iptv_dests[dest].progs[j].source_pn);
                    document.iptv.elements["source*"].options[idx].selected=true
                    }
                }
                }
            
            // pass in a prot and program and get the index of the matching source
            function findsource(port, program)
                {
                for (i = 0; i &lt; avail_progs.length; i++)
                    {
                    //alert(avail_progs[i].port+","avail_progs[i].pn);
                    if (port == avail_progs[i].port &amp;&amp; program == avail_progs[i].pn)
                    {
                    //alert(avail_progs[i].name
                    return i;
                    break;
                    }
                    }
                    return -1; //not found
                }
                
            
            
            function showsourceprograms()
                {
                clearselected();
                showsources();
                }
            
            // not used
            // Resets the form to original values.
            function resetforms()
                {
                // save currenlty selected destination
                sel = document.iptv.dest.selectedIndex;
                // clear the form
                document.iptv.reset();
                // set the formerly selected destinations
                document.iptv.dest.options[sel].selected=true;
                // set the sources
                showsources();
                }
            
            
            /*
            *  Function to delete destingation.
            *
            */
            function deletedest(idx)
                {
                if (idx != -1)   // enure something selected.
                    {
                    var answer = confirm("Delete destination "+iptv_dests[idx].dest_ip_addr+","+iptv_dests[idx].dest_ip_port+"?")
                    if (answer)
                    {
                        del(idx);  // make the ajax call
                        document.iptv.dest.options[idx]= null;  // remove the select in the form
                        iptv_dests.splice(idx,1);        // remove from the array
                    }
                    }
                }
            
            function del(idx) {
                var getstr = "?del="+document.iptv.dest.options[idx].value+"&amp;action=apply&amp;function=delete";
                makeRequest('/asimux/iptv.py', getstr);
                }
            
            // ************** end delete handler
            
            // *** start
            
            
            /**************************************************************************
            *  add new dest handling
            */
            function addnew(obj)
            {
            var newIP=document.getElementById('newIP');
            var newPort=document.getElementById('newPort');
            var newDev=document.getElementById('newDev');
            
            if (validatenew(newIP.value, newPort.value, newDev.value))
                {
                getnew(obj);
                //console.log(newIP.value+","+newPort.value+","+newDev.value);
                add_dest_array(newIP.value, newPort.value, newDev.value);
                add_to_select(newIP.value, newPort.value, newDev.value);
                //showsourceprograms();
                }
            }
            
        
            function getnew(obj) {
            var getstr = "?";
            //alert(obj.childNodes.length);
            for (i=0; i &lt; obj.childNodes.length; i++) {
                if (obj.childNodes[i].tagName == "INPUT") {
                if (obj.childNodes[i].type == "text") {
                    getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&amp;";
                }
                if (obj.childNodes[i].type == "checkbox") {
                    if (obj.childNodes[i].checked) {
                    getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&amp;";
                    } else {
                    getstr += obj.childNodes[i].name + "=&amp;";
                    }
                }
                if (obj.childNodes[i].type == "radio") {
                    if (obj.childNodes[i].checked) {
                    getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&amp;";
                    }
                }
                }
                if (obj.childNodes[i].tagName == "SELECT") {
                var sel = obj.childNodes[i];
                getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&amp;";
                }
            }
            getstr+="action=apply&amp;function=new";
            makeRequest('/asimux/iptv.py', getstr);
            }
            
            
            function add_to_select(ip, port1, dev)
            {
            document.iptv.dest.options[document.iptv.dest.options.length] = new Option(ip+","+port1, iptv_dests.length-1);
            }
            
            
            function add_dest_array (ip, port, dev)
            {
                iptv_dests.push( new TIptvDestination( ip,
                    port, dev,
                    1, 0,
                    1, null ) );
            }
            
            // Tests for numeric input
            function isNumber(inputStr)
            {
            for (var i = 0; i &lt; inputStr.length; i++)
                {
                var oneChar = inputStr.substring(i, i + 1)
                if (oneChar &lt; "0" || oneChar &gt; "9")
                {
                alert("Please make sure entries are numbers only.");
                return false;
                }
                }
                return true;
            }
            
            /****************************************
            *  verifies input for new dest  */
            function validatenew(ipa, portnum, dev)
            {
            if (!verifyIP(ipa))
                {
               // document.newdest.ip.focus()
                }
            if (!validateport(portnum))
                {
               // document.newdest.portnum.focus()
                }
            else
                {
                return true;
                }
            }
            
            function validateport(portnum)
            {
            if (isNumber(portnum))
                {
                if (portnum &gt; 0 &amp;&amp; portnum &lt; 65536 )
                {
                return true;
                }
                else
                {
                alert("Invalid Port, use 1-65535");
                return false;
                }
                }
            else
                {
            //    alert("Please make sure entries are numbers only.");
                return false;
                }
            }
            
            // Returns true for valid Address
            function verifyIP (IPvalue)
            {
            errorString = "";
            theName = "IPaddress";
            
            var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
            var ipArray = IPvalue.match(ipPattern);
            
            if (IPvalue == "0.0.0.0")
                errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
            else if (IPvalue == "255.255.255.255")
                errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
            if (ipArray == null)
                errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
            else
                {
                for (i = 0; i &lt; 4; i++)
                {
                thisSegment = ipArray[i];
                if (thisSegment &gt; 255)
                    {
                    errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
                    i = 4;
                    }
                if ((i == 0) &amp;&amp; (thisSegment &gt; 255))
                    {
                    errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
                    i = 4;
                    }
                }
                }
            extensionLength = 3;
            if (errorString == "")
                {
                //alert ("That is a valid IP address.");
                return true
                }
            else
                {
                alert (errorString);
                return false
                }
            }
            
            /******   End add new handing ***************************************
            ********************************************************************/
            
            
            // Sets the default values for the new dest.
            function setdefaults ()
            {
            //document.newdest.ip.value=base_ip_addr;
            //document.newdest.portnum.value=default_ip_port;
            //document.newdest.ttl.value=default_ip_ttl;
            //document.newdest.device.selectedIndex=getindexfordevice(default_network_if);
            //document.newdest.patrate.value="1";
            //document.newdest.constrate.value="0";
            }
            
            // return the index for the device select box
            // just hard coded for now.  Need to dynamically look up.
            function getindexfordevice(device)
            {
            if (device == "eth0")
        {
        return 0;
        }
            if (device == "eth1")
        {
        return 1;
        }
            return -1;
            }
        
        
            function load()
            {
            showavail();
            showdest();
            setdefaults();
			document.getElementById("apply").style.display="none";
			<!-- item.style.display = 'none'; -->
            }

            
        <xsl:apply-templates mode="iptv"/>
    
        </script>
    
        </head>
    </xsl:template>


    <xsl:template match="text()" mode="iptv"/>
	<!--xsl:template name="getServiceName">
        <xsl:param name="statusProgram" />
        <xsl:param name="aIndex" />
        <xsl:param name="aProgramNumberIn" />
        <xsl:choose>
        <xsl:when test="">
        <xsl:value-of select="/configuration/port[@index=$aIndex]/program_remap/program[@program_number_in=$aProgramNumberIn]/name_out" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="substring-before($statusProgram/@name, '(')" />
        </xsl:otherwise>
        </xsl:choose>
    </xsl:template-->



</xsl:stylesheet>
