var constants           = new ConstantControl();
var TestControl         = Class.create();
               
TestControl.prototype = {
                 
	initialize : function(accessCode) {
	
		var errorMessage    = "TestControl.prototype.initialize: unable to load xml";
		
		try 
	    {
	            TestControl.prototype.AccessCode                   = accessCode;
	            TestControl.prototype.Section                      = "tests";
	            TestControl.prototype.HeaderTemplate               = templateControl.getData("TEST_VIEW_ITEMS_HEADER"); 
	            TestControl.prototype.FooterTemplate               = templateControl.getData("TEST_VIEW_ITEMS_FOOTER"); 
	            TestControl.prototype.XmlUrl                       = constants.TEST_SERVICE_URL;
	            TestControl.prototype.TemplateUrl                  = constants.TEST_TEMPLATE_URL;
                TestControl.prototype.ControlId                    = "MY_TEST_PANEL_CONTENT";   
                TestControl.prototype.DataSource                   = "test"; 
                TestControl.prototype.ItemTemplate                 = templateControl.getData("TEST_VIEW_ITEMS"); 
                TestControl.prototype.SeparatorTemplate            = "";    
                TestControl.prototype.AlternatingItemTemplate      = templateControl.getData("TEST_VIEW_ITEMS");    

                TestControl.prototype.ReloadFunction               = "testControl.get";
                TestControl.prototype.Data                         = null;
                
                TestControl.prototype.PagingControlId              = "MY_TEST_PANEL_CONTENT_PAGING";
                TestControl.prototype.CurrentPage                  = "";
                TestControl.prototype.PageCount                    = "";
                TestControl.prototype.PageSize                     = 10;
                TestControl.prototype.Step                         = 10;
                TestControl.prototype.PageCount                    = 0;
                TestControl.prototype.PagingHeaderTemplate         = "[ ";
                TestControl.prototype.PagingItemTemplate           = "<a href=\"javascript:{#reloadfunction}({#page})\" >{#title}</a> &nbsp; ";
                TestControl.prototype.PagingSelectedItemTemplate   = "{#title} &nbsp; ";
                TestControl.prototype.PagingFooterTemplate         = " ]";
                TestControl.prototype.xmlChartData                 = null;
                
                TestControl.prototype.nrtLink                     = "http://chart.apis.google.com/chart?cht=lc&chs=550x300&chxr=1,0,100&chco=6ECD00&chxt=x,y&chg=0,10&chls=3,0,0&chxs=0,000000,10,0,lt|1,000000,10,0,lt&chxtc=0,10|1,10";
                TestControl.prototype.vrtLink                     = "http://chart.apis.google.com/chart?cht=lc&chs=550x300&chxr=1,0,100&chco=1FA3C9&chxt=x,y&chg=0,10&chls=3,0,0&chxs=0,000000,10,0,lt|1,000000,10,0,lt&chxtc=0,10|1,10";
                TestControl.prototype.lrtLink                     = "http://chart.apis.google.com/chart?cht=lc&chs=550x300&chxr=1,0,100&chco=ff7c00&chxt=x,y&chg=0,10&chls=3,0,0&chxs=0,000000,10,0,lt|1,000000,10,0,lt&chxtc=0,10|1,10";
                
                TestControl.prototype.testId                      = 0;
                TestControl.prototype.testCount                   = 0;
                
    	}
    	catch(e) 
        {
            TestControl.prototype.error(errorMessage,e);
        }  				
	},
	dataBind :function(){
	
	    var htmlString = "";
        htmlString += TestControl.prototype.HeaderTemplate;
        
        
        for(var count=0;count<TestControl.prototype.Data.length;count++){
            var node = TestControl.prototype.Data[count];
            var row =  TestControl.prototype.ItemTemplate;
            
            if(TestControl.prototype.AlternatingItemTemplate != "" && (count+1)% 2 == 0 ){
                row =  TestControl.prototype.AlternatingItemTemplate
            }
           
            for (var i = 0; i < node.attributes.length; i++){
			    var re = new RegExp("{@" + node.attributes[i].nodeName + "}","g");
			    row = row.replace(re,node.attributes[i].nodeValue);
		    }
    		
		    for (var i = 0; i < node.childNodes.length; i++){
		        if(node.nodeType != 3 && node.childNodes[i].firstChild != null){
			        var re = new RegExp("{\\$" + node.childNodes[i].nodeName + "}","g");
			        row = row.replace(re,node.childNodes[i].firstChild.nodeValue);
			    }
		    }
    		
		    // eval javascript
		    evalRe = new RegExp("{Eval(.*?)}","g");
    		
		    myArray = row.match(evalRe);
    		
		    if(myArray != null){
		        for(var i=0;i<myArray.length;i++){
		            var result = eval(myArray[i].replace(evalRe,"$1"));
		            row = row.replace(myArray[i],result);
		        }
		    }
            
            htmlString += row;
            
            if(TestControl.prototype.SeparatorTemplate != "" && count + 1 != TestControl.prototype.Data.length){
                htmlString += TestControl.prototype.SeparatorTemplate;
            }
        }
        
        htmlString += TestControl.prototype.FooterTemplate;
        
        $(TestControl.prototype.ControlId).innerHTML = htmlString;
	},
	pagerBind : function(){
	    var result = "";
    
        if(TestControl.prototype.PageCount > 1){
            result += TestControl.prototype.PagingHeaderTemplate;
            var startPoint = Math.floor((TestControl.prototype.CurrentPage/TestControl.prototype.Step)) * TestControl.prototype.Step;
            if((TestControl.prototype.CurrentPage % TestControl.prototype.Step) == 0) {
                startPoint -= TestControl.prototype.Step;
            }
            
            if(startPoint >= TestControl.prototype.Step){
                result += TestControl.prototype.PagingItemTemplate.replace("{#page}",startPoint).replace("{#title}","...").replace("{#reloadfunction}",TestControl.prototype.ReloadFunction);
            }
            
            for(var i=startPoint +1;i<=TestControl.prototype.PageCount && i<=(startPoint + TestControl.prototype.Step);i++){
                if(i != TestControl.prototype.CurrentPage){
                    result += TestControl.prototype.PagingItemTemplate.replace("{#page}",i).replace("{#title}",i).replace("{#reloadfunction}",TestControl.prototype.ReloadFunction);
                }else{
                    result += TestControl.prototype.PagingSelectedItemTemplate.replace("{#title}",i);
                }
            }
            
            if(startPoint < (TestControl.prototype.PageCount - TestControl.prototype.Step)){
                result += TestControl.prototype.PagingItemTemplate.replace("{#page}",(startPoint + TestControl.prototype.Step +1)).replace("{#title}","...").replace("{#reloadfunction}",TestControl.prototype.ReloadFunction);
            }
            result += TestControl.prototype.PagingFooterTemplate;
        }
        
        $(TestControl.prototype.PagingControlId).innerHTML = result;
	},
	loadVars : function(request){

        var errorMessage        = "TestControl.prototype.loadVars";
        try
        {

	       if(parseInt(request.responseXML.documentElement.getElementsByTagName('tests')[0].getAttribute('count')) > 0)
	       {
	            TestControl.prototype.CurrentPage                             = request.responseXML.documentElement.getElementsByTagName('PagingData')[0].getAttribute('currentPage');
                TestControl.prototype.PageCount                               = request.responseXML.documentElement.getElementsByTagName('PagingData')[0].getAttribute('pageCount');
	            TestControl.prototype.Data                                    = request.responseXML.documentElement.getElementsByTagName(TestControl.prototype.DataSource);  
	            TestControl.prototype.xmlChartData                            =	request.responseXML.documentElement.getElementsByTagName("Chart");
	            TestControl.prototype.testCount                               = parseInt(request.responseXML.documentElement.getElementsByTagName('tests')[0].getAttribute('count'));
	            TestControl.prototype.getData();
	       }
	       else
	       {
	            $(TestControl.prototype.ControlId).update("Sorry you have not taken any tests matching the filtered criteria.");
	       }
	       
	    }
	    catch(e) 
        {
            TestControl.prototype.error(errorMessage,e);
        }
	},
	getData : function(){
        var errorMessage    = "TestControl.prototype.getData";
        try 
	    {
	            if(TestControl.prototype.Data != null)
	            {
                    TestControl.prototype.dataBind();
                    TestControl.prototype.pagerBind();
                    TestControl.prototype.getChartData();
                }
	    }
	    catch(e) 
        {
            TestControl.prototype.error(errorMessage,e);
        } 
	},
	
	getChartData : function(){

   
	        var chart_1_data = TestControl.prototype.xmlChartData[0].firstChild.nodeValue;
	        var chart_2_data = TestControl.prototype.xmlChartData[1].firstChild.nodeValue;
	        var chart_3_data = TestControl.prototype.xmlChartData[2].firstChild.nodeValue;
        	
	        var chart_1_title = "The graph below depicts your performance status to date. The graph shows your percentile score for each NRT test (up to 10), in the order that you completed it.";
	        var chart_2_title = "The graph below depicts your performance status to date. The graph shows your percentile score for each VRT test (up to 10), in the order that you completed it.";
            var chart_3_title = "The graph below depicts your performance status to date. The graph shows your percentile score for each LRT test (up to 10), in the order that you completed it.";
        	
	        if(chart_1_data != "NULL")
	        {
	            $("CHART_1").src= TestControl.prototype.nrtLink + chart_1_data;
	            $("CHART_1_TITLE").update(chart_1_title);
	            $("CHART_1_DIV").show();
	            $("CHART_1_TITLE").show();
	            $("ERROR_PANEL").hide();
	        }
	        else
	        {
	            $("CHART_1_DIV").hide();
	            $("CHART_1_TITLE").hide();
	            $("ERROR_PANEL").hide();
	        }
        	
	        if(chart_2_data != "NULL")
	        {
	            $("CHART_2").src= TestControl.prototype.vrtLink + chart_2_data;
	            $("CHART_2_TITLE").update(chart_2_title);
	            $("CHART_2_DIV").show();
	            $("CHART_2_TITLE").show();
	            $("ERROR_PANEL").hide();
	        }
	        else
	        {
	            $("CHART_2_DIV").hide();
	            $("CHART_2_TITLE").hide();
	            $("ERROR_PANEL").hide();
	        }
	        
	        if(chart_3_data != "NULL")
	        {
	            $("CHART_3").src= TestControl.prototype.lrtLink + chart_3_data;
	            $("CHART_3_TITLE").update(chart_3_title);
	            $("CHART_3_DIV").show();
	            $("CHART_3_TITLE").show();
	            $("ERROR_PANEL").hide();
	        }
	        else
	        {
	            $("CHART_3_DIV").hide();
	            $("CHART_3_TITLE").hide();
	            $("ERROR_PANEL").hide();
	        }
        
	},
	get : function(p){
	    
	    $("CHART_1_DIV").hide();
	    $("CHART_2_DIV").hide();
	    $("CHART_3_DIV").hide();
	    $("CHART_1_TITLE").hide();
	    $("CHART_2_TITLE").hide();
	    $("CHART_2_TITLE").hide();
	    $("ERROR_PANEL").update("");
	    $("ERROR_PANEL").hide();
	    
	    $(TestControl.prototype.ControlId).update("");
	    $(TestControl.prototype.PagingControlId).update("");
	    
	    var errorMessage    = "TestControl.prototype.get";
	    
	    var testId          = $("testList").value;
        var url             = TestControl.prototype.XmlUrl + "?testId=" + testId + "&p=" + p + "&ps=" + TestControl.prototype.PageSize + "&ac=" + TestControl.prototype.AccessCode;
        var myAjax          = null;


	    function ajaxError(e){
	        TestControl.prototype.error(errorMessage,e);
	    }
	    
	    try  
	    {     
              myAjax  = new Ajax.Request(url,{method:'get',onSuccess:TestControl.prototype.loadVars,onFailure:ajaxError,asynchronous:false});  
	    } 
	    catch(e) 
	    {
	        TestControl.prototype.error(errorMessage,e);
	    } 
	
	},
	reload: function(p){
	    TestControl.prototype.get(1);
	},
	error : function(errorMessage,e){
	    alert(errorMessage + "\n\n" + "-- " + e + " --");
	}
}