var original_table_width;
var values = Array();
var isTwinpack = false;
var trigger;
var rowId = 0;

var target_products =  Array();

function convertToXml(data)
{
	if (typeof data == "string") {
		xml = new ActiveXObject("Microsoft.XMLDOM");
		xml.async = false;
		xml.loadXML(data);
		return xml;
	} else {
		return data;
	}
}


// Add inArray method
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
        var i;
        for (i=0; i < this.length; i++)
        {
                // Matches identical (===), not just similar (==).
                if (this[i] === value)
                {
                        return true;
                }
        }
        return false;
};

// Loads the essentials data from the PS XML
// Reads ps_essentials.xml
function load_products()
{
        values = Array();
        $.ajax({
                url: xml_path + "ps_" + filename + ".xml",
                async: false,
                dataType: ($.browser.msie) ? "text" : "xml",
                success: function(data){
                        var xml = convertToXml(data);
                        $(xml).find('product').each(function(){
                                var bcode = $(this).attr('bcode');
        
                                if (keys.inArray(bcode))
                                {
                                        var obj = new Object();
                                        obj.pname = $(this).attr('pname');
        
                                        var row_values = Array();
                                        $(this).find('row').each(function(){
                                                var row_id = $(this).attr("id");
                                                var row_value = $(this).text();
                                                row_values[row_id] = row_value;
                                        });
        
                                        obj.rows = row_values;
                                        values[bcode] = obj;
                                }
                        });
            
                        //build_table_body();
                }
        });
        
        var product_code = Array();
        
        $.ajax({
                url: xml_path + "ps_products.xml",
                async: false,
                dataType: ($.browser.msie) ? "text" : "xml",
                success: function(data){
                        var xml = convertToXml(data);
                        $(xml).find('product').each(function(){
                                var vcode = $(this).attr('vcode');
                                var row_value = $(this).text();
                                product_code[row_value] = vcode;
                        });
            
                        for(i=0; i < keys.length; i++)
                        {
                                var obj = values[keys[i]];
                                obj.vcode = product_code[obj.pname];
                                values[keys[i]]= obj;
                        }
                        
                        build_table_body();
                }
        });
}


// Build the table body
// Reads the data from the PS XML
// Reads ps_tablelegend.xml
function build_table_body()
{
        $.ajax({
                url: xml_path + "ps_tablelegend.xml",
                dataType: ($.browser.msie) ? "text" : "xml",
                success: function(data){
                        var tbody_html = '';
                        var xml = convertToXml(data);
                        var products = $(xml).find(filename);
                        
                        if(isTwinpack == true && filename == 'essentials')
                        {
                                // Insert header row here?
                                tbody_html += '<tr class="head">' + $("table.uber tr.head").html() + '</tr>';
                        }
                        
                        $(products).find("row").each(function(){
                                rowId++;
                                
                                var id = parseInt($(this).attr("id"));
                                var waiting_period = $(this).attr("waiting");
                                var tool_tip =  $(this).attr("tooltip");
                                var description = $(this).text();
                                
                                if ( !(isTwinpack == false && id == 1 && filename == 'essentials') )
                                {
                                
                                        var class_name;
                                        var cell_html;
                        
                                        // Alternating the table rows
                                        if( rowId % 2 == 0 )
                                        {
                                                class_name = "odd";
                                        }
                                        else
                                        {
                                                class_name = "even";
                                        }
                        
                                        tbody_html += '<tr class="' + class_name + '">\n';
                                        tbody_html += '\t<td><span class="left">' + description + '</span>';
                                        
                                        if( tool_tip.length > 0 )
                                        {
                                            tbody_html += '<span class="right"><img src="' + website_path + '/Images/table/icon_help.gif" alt="" title="' + tool_tip + '" /></span>\n';
                                        }
                                        
                                        tbody_html += '</td>\t<td>' + waiting_period + '</td>\n';
                        
                                        // Setp over the essentials to mark if they are available or not
                                        for(i=0; i<keys.length; i++)
                                        {
                                                data = values[keys[i]].rows[id];
                                                tip_html = '';
                                                if (data == 'y')
                                                {
                                                        cell_html = '<img src="' + website_path + '/Images/table/icon_tick.png" alt="" />';
                                                }
                                                else if (data == 'n')
                                                {
                                                        cell_html = '<img src="' + website_path + '/Images/table/icon_cross.png" alt="" />';
                                                }
                                                else if (data == 'yif' || data == 'y*')
                                                {
                                                        cell_html = '<img src="' + website_path + '/Images/table/icon_tick_conditions.png" alt="" />';
							if( filename == 'essentials' )
							{
								tip_html = ' title="If selected."';
							}
							else
							{
								tip_html = ' title="Limited benefits apply which are similar to the cost of a shared room in a public hospital."';
							}
                                                }
                                                else
                                                {
                                                        cell_html = data;
                                                }
                        
                                            
                                                tbody_html += '\t<td class="' + class_name + ' ' + keys[i] + ' center icon" ' + tip_html + '>' + cell_html + '</td>\n';
                                        }
                                        tbody_html += '</tr>\n\n';
                                }
                
                        });
                        
                        // Dumpt the table body into the DOM
                        $("div.table_box table tbody").append(tbody_html);
                        
                        if(isTwinpack == true && filename == 'hospital')
                        {
                                filename = 'essentials';
                                load_products();
                        }
                        else
                        {
                                page_loaded();
                        }
                }
        });
}

function page_loaded()
{
        // Assign the Tooltips
        $("td span.right img[class!=waitingPeriods], td.icon").tooltip({
                showURL: false,
                track: true
        });
        
        $("td span.right img.waitingPeriods").tooltip({
                showURL: false,
                track: true,
                bodyHandler: function() {
			var html = $(this).siblings("div.tooltip").html();
			return html;
		}

        });
        
    for ( i = 0; i < keys.length; i++ )
    {
        $("table.uber tr").each(function() { $(this).children("td").eq(i+2).addClass(keys[i]) });
        $("table.uber tr.head").each(
                function()
                {
                        $(this).children("td").eq(i+2).html(values[keys[i]].pname);
                }
        );
        $("table.uber tfoot td").eq(0).addClass('empty');
    }
    
    $("table.uber tr").each(function() { $(this).children("td:gt(" + (keys.length+1) + ")").remove() });
    
    // Hide functionality
    $("table.uber thead tr.control td").click(function(){
            var row_width = $(this).width();
    
            var hide_class = $(this).attr("class").replace(/\s*action\s*/,"");
            
            $("table.uber td." + hide_class).hide();
            var old_width = $("table.uber").css("width").replace(/px/, "");
            var new_width = parseInt(old_width,10) - row_width - 12;
            $("table.uber").css("width", new_width + "px");
    
    });
    
    // Show all
    $("table.uber thead td.top_left span.show_all_products").click(function(){
            $("td").show();
            $("table.uber").css("width", original_table_width);
    });
    
    replaceUber();
}

/*
 * Function to relaocate the overlay html src code to teh end of the page
 */
function relocate_hover_html()
{
        var html = $("#overlay_src_container").html();

	$("#overlay_src_container").html("");
	$('body').append(html);

}

$(document).ready(function(){
    original_table_width = $("table.uber").css("width");
    
    // Special case for twinpacks - load hospital and essentials
    if(filename == 'twinpack')
    {
        isTwinpack = true;
        filename = 'hospital';
        load_products();
    }
    else
    {
        load_products();
    }
    
    // Put the code on the right spot, at the end of the document.
    relocate_hover_html()
    
    // Put the product code into the form
    $("table tfoot img").click(function(i){
        var  type = $(this).parent().attr('class').replace(/\s*center\s*/, "");
        
        //console.log("clicked " + type + " --> "  + values[type].vcode);
	$(":input#promoV1").val(values[type].vcode);
    });
   
    trigger = $("table tfoot img").overlay({
                // some expose tweaks suitable for modal dialogs
		expose: {
                        color: '#000000',
                        loadSpeed: 200,
                        opacity: 0.35,
                        zIndex: 3000
                },
		onLoad: function(){
                        replaceH2();	
                },
                top: 'center',
                closeOnClick: true
                
        });

         $("#form_quote").submit(function(){
                $(trigger).each(function(i){
					try
					{
						$(trigger).eq(i).overlay().close();
					}
					catch ( exeception )
					{
					}
					
                });
        });

        // create the calender for the product selector
        $('#dob').datepicker({
                dateFormat: 'yy-mm-dd',
                defaultDate: new Date(1950,0,1),
                yearRange: '1909:1992',
                changeMonth: true,
                changeYear: true,
                onChangeMonthYear: function(year, month, inst) {			
                        // Get selected date
                        var selected_date = $(this).val();
                        // Add preceding 0 if needed
                        if(month < 10)
                        {
                                month = "0" + month;
                        }
                        
                        // Retrieve the selected day and add a preceding 0 if needed
                        var day =  parseInt(selected_date.substr(8),10);
                        
                        if (isNaN(day))
                        {
                                day = 1;
                        }
                        
                        if( day < 10 )
                        {
                                day = "0" + day
                        }
                        
                        // Build the new date
                        $(this).val(year + "-" + month + "-" + day);	
                }
        });
        // also attach it to the icon
        $("#dobCalendar").click( function() { $('#dob').datepicker("show") } );
        
        $("#ui-datepicker-div").css("z-index", 4000);
    
    
    
    
    
    
});	
