var fileArray = 
[
//  ["stable",      "/download/voyage/voyage-0.5.2.tar.bz2",    "0.5.2" ],
//  ["stable cd",   "/download/ISO/voyage-0.5.2.iso",       "live cd" ],

    ["stable",      "/download/voyage/voyage-0.6.5.tar.bz2",    "0.6.5" ],
    ["stable cd",   "/download/ISO/voyage-0.6.5.iso",       "live cd" ],
    ["stable sdk cd",   "/download/ISO/sdk/voyage-sdk-0.6.5.iso",   "sdk" ],
   
    ["stable amd64","/download/voyage/amd64/voyage-0.6.5_amd64.tar.bz2",    "0.6.5" ],
    ["stable amd64 cd",     "/download/ISO/amd64/voyage-0.6.5_amd64.iso",   "live cd" ],

//  ["devel",       "/download/voyage/voyage-0.6.5.tar.bz2",    "0.6.5" ],
//  ["devel cd",    "/download/ISO/voyage-0.6.5.iso",       "live cd" ],
//  ["devel sdk cd",    "/download/ISO/sdk/voyage-sdk-0.6.5.iso",   "sdk" ],

//  ["devel amd64","/download/voyage/amd64/voyage-0.6.5_amd64.tar.bz2",     "0.6.5" ],
//  ["devel amd64 cd",  "/download/ISO/amd64/voyage-0.6.5_amd64.iso",   "live cd" ],

	["daily", 		"/download/voyage/voyage-current.tar.bz2", 	"daily" ],
	["daily cd", 	"/download/ISO/voyage-current.iso", 		"live cd" ]

//	["experimental", 		"/download/voyage/voyage-lenny.tar.bz2", 	"experimental" ],
//	["experimental cd", 	"/download/ISO/voyage-lenny.iso", 		"live cd" ]
];

var formObj = null;
var formObjTyp = "";
var request=null;
var mirrorData=null;

window.onload=function()
{
	var mirror = document.getElementById("mirror");
	if (mirror != null)
	{
		mirror.onclick=function(){ mirrorSelected(this); };
		mirror.onchange=function(){ mirrorSelected(this); };
		//mirror.onchange=function(){ mirrorSelected(this); };
		mirror.onload=function(){ mirrorSelected(this); };
		generateList(mirror);	
	}
}

function getMirrorURL(_name)
{
	for(var i=0; i < mirrorData.length; i++)
    {
    	if (mirrorData[i][0] == _name)
    		return mirrorData[i][1];
    }
    return null;
}

function mirrorSelected(obj)
{

	var fld = document.getElementById("select_info");
	var mirror = document.getElementById("mirror");
	if (mirror != null)
    {
    	var opt = getSelectInfo(mirror);

		//alert ("mirror width = " + mirror._width);

        var mirrorURL = getMirrorURL(opt.value);
        if (mirrorURL != null)
		{
        	setMirrorURL(mirrorURL );
			
			//	the following code is for download page.
			if (hasDownloadClass() == 1)
			{
				replaceMirrorURL(mirrorURL);
			}	
		}

	    if (fld != null)
	    {
	        fld.innerHTML =  opt.value + " ; " + getMirrorURL(opt.value)
	        					  + " selected";
	    }    
	}
}

function replaceMirrorURL(mirrorURL)
{
	var anchorArrary = document.getElementsByTagName("a");
		
	for (var i=0; i < anchorArrary.length ; i++)
	{
		var obj = anchorArrary[i];
		var parentobj = obj.parentNode;
			
		var parentNodeName = obj.parentNode.nodeName.toLowerCase();
		if ( parentNodeName== "li" && isDownload(obj.href) )
		//if ( isDownload(obj.href) )
		{
			var str = obj.href;

			var uri="http://";
			var slash="/";

			var str1=str.slice(str.indexOf(uri) + uri.length);
			var str2=str1.slice(str1.indexOf(slash));

			obj.href = mirrorURL + str2;
																						}
																					}
}

function isDownload(fullURI)
{
	var substr=[ ".tar.gz" , ".iso" , ".tar.bz2", "download/voyage" ];
																					for (var i = 0; i < substr.length ; i++)
	{
		if (fullURI.indexOf(substr[i]) > 0)
			return true;
	}

	return false;
}

function hasDownloadClass()
{
	var divArrary = document.getElementsByTagName("div");
	for (var i=0; i < divArrary.length ; i++)
	{
		var obj = divArrary[i];
		if (obj.className == "download")
			return 1;
	}
	return 0;
}

function setMirrorURL(url)
{
	for(var i=0; i < fileArray.length; i++)
    {
    	var _opt = document.getElementById(fileArray[i][0]);
    	if ( _opt != null)
        {
            href = url + fileArray[i][1];
            
            _opt.href=href;
            _opt.innerHTML=fileArray[i][2];
        }
    }
}

function generateList(obj)
{
    if (obj == null ) { return; }
    //if(obj.checked) {
        formObj = obj;
        formObjTyp = formObj.tagName.toLowerCase();
        var url = "/files/linux/js/mirror_data.js";
        httpRequest("GET",url,true);
    //}
}

function getSelectInfo(selectObj)
{
    if (selectObj == null) { return null; }
    formObj=selectObj;
    formObjTyp = formObj.tagName.toLowerCase();
    var optsArray = formObj.options;
    var selectedArray = new Array();
    var val = "";
    for(var i=0,j=0; i < optsArray.length; i++)
    {
        if(optsArray[i].selected) 
        {
            selectedArray[j]=optsArray[i];
            j++;
        }
    }

    if (selectedArray.length > 0)
    	return selectedArray[0];
    else 
    	return val;
}

//event handler for XMLHttpRequest
function handleResponse(){
    try{
        if(request.readyState == 4){
            if(request.status == 200){
                if(formObjTyp.length > 0 && formObjTyp == "select")   {    //working with existing radio button
                    var resp =  request.responseText;
                    if (resp != null){
                        //return value is a JSON array
                        mirrorData = null;
                        mirrorData = eval(resp);
                        
                        var newsel = document.getElementById("mirror");
                        reset(newsel);
                        createOptions(newsel, mirrorData);
                        
                        //	at last, select default mirror
                        mirrorSelected(this);
                    }
                }
            } else {
                //request.status is 503  if the application isn't available; 500 if the application has a bug
                alert(
                        "A problem occurred with communicating between the XMLHttpRequest object and the server program.");
            }
        }//end outer if
    } catch (err)   {
        alert("It does not appear that the server is available for this application. Please"+
              " try again very soon. \nError: "+err.message);

    }
}

function createOptions(sel,_options) {
    //_options is an array of strings that represent the values of
    //a select list, as in each option of the list. sel is the select object
    if(_options == null || _options.length==0) { return;}
    var opt = null;
    for(var i = 0; i < _options.length; i++) {
        opt = document.createElement("option");
        opt.appendChild(document.createTextNode(_options[i][0]));        
        opt.value = _options[i][0];        
        sel.appendChild(opt);
    }
}
//remove any existing children from an Element object
function reset(elObject){
    if(elObject != null && elObject.hasChildNodes()){
        for(var i = 0; i < elObject.childNodes.length; i++){
            elObject.removeChild(elObject.firstChild);
        }
    }
}
/* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool){
    try{
        /* Specify the function that will handle the HTTP response */
        request.onreadystatechange=handleResponse;
        request.open(reqType,url,bool);
        request.send(null);
    } catch (errv) {
        alert(
                "The application cannot contact the server at the moment. "+
                "Please try again in a few seconds." );
    }
}
/* Wrapper function for constructing a Request object.
 Parameters:
  reqType: The HTTP request type such as GET or POST.
  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not. */
function httpRequest(reqType,url,asynch){
    //Mozilla-based browsers
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject){
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (! request){
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }
    //the request could still be null if neither ActiveXObject
    //initializations succeeded
    if(request){
       initReq(reqType,url,asynch);
    }  else {
        alert("Your browser does not permit the use of all "+
        "of this application's features!");}
}
