﻿//Globals live here.
var controls; //This is the main array of control data, as parsed from the JSON. Update this, and render this on changes.
var quoteParameters;
var ready; //This is to signal that the page is ready for user interaction.
var DisableUpdate;
var currentFocus = null;
var Busy = false;
var OutstandingSave = false;
var NumberOfTabs = 0;
var Adding = false;


function log(msg) {
    setTimeout(function() {
        //throw new Error(msg);
        //console.log(msg);
    }, 0);
}

function displayPleaseWait()
{
    $('#progress').dialog({open: true, 
                           modal: true, 
                           closeOnEscape: false,  
                           draggable: false, 
                           resizable: false, 
                           beforeclose: function(event, ui) { return ready; }});
    $('#progress').dialog('open');
    //save focus
    //$("#myForm input").attr("readonly", "readonly");

    //will be unbound by bindeventhandlers
}

function escapeQuotes(input)
{
    if (typeof(input) == "boolean")
    {
        return input.toString();
    }
    else
    {
        return input.replace( "\"", "\\\"");
    }
}

function returnFocus()
{
	try
	{
		$('#'+currentFocus).find('.value').not('.hasDatepicker')[0].focus();
	}
	catch (err)
	{
	
	}
}
function closePleaseWait()
{
    $('#progress').dialog('close');
    $('#progress').dialog('destroy');
    //$("#myForm").show("", {}, 500);
    //$("#myForm input").removeAttr("readonly", "readonly");
    //alert(this);
    //$(currentFocus).focus();
    //refocus
}

function readyToGo() {
   
    $('#bpSaveButton').val(ConfigSaveButtonCaption);
    
    if( ConfigResetButton )
    {
      $('#bpSaveButton').after('<input type="button" value="Reset" id="bpResetButton" class="ui-widget-content bpButton"/>');
      $('#bpResetButton').bind('click', reset);
    }
	
	if (ConfigShowAddButton)
    {
        $('#bpSaveButton').after('<input type="button" value="Add" id="bpAddButton" class="ui-widget-content bpButton"/>');
        $('#bpAddButton').bind('click', add);
    }
    
    AddNextTab();
	
	if (ConfigImageButtons)
	{
            $('#bpSaveButton').val('');
            $('#bpResetButton').val(''); 
            $('#bpAddButton').val('');
            if (ConfigNextInsteadOfSave)
            {
                $('#bpNextButton').val('');
            }
            
	}
        
    
    $(document).ajaxError(function(err)
    {   
      DisplayError(err.Message);
    });
    
    
    
    //$.ajaxSetup("timeout : 50000");
    
    //Enhanced/Overridden/workaround xhr (XMLHttpRequest creation function) required for AJAX in 
    //IE with activex controls disabled.
    $.ajaxSetup({
        timeout: 50000,
        xhr: function()
        {
                if (window.XMLHttpRequest)
                {
                        return new XMLHttpRequest();
                }
                else
                {
                        var progIDs = ['Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];

                        for (var i = 0; i < progIDs.length; i++)
                        {
                                try
                                {
                                        var xmlHttp = new ActiveXObject(progIDs[i]);
                                        return xmlHttp;
                                }
                                catch (ex)
                                {
                                }
                        }

                        return null;
                }
        }
    });
        
    
    DisableUpdate = false;
    ready = false;
    $("#bpSaveButton").bind("click", save);
    $("#bpCancelButton").bind("click", cancel);
    displayPleaseWait();
    AlertIfOldIE();
    
    jQuery(window).unload(function(e){
      //alert("unload "+e)
      })
    
	//$.get("Quote.aspx?quote="+quoteId, gotQuoteParameters, "text");
	$.ajax({
	  type: "GET",
	  url: "Quote.aspx",
	  data: "",
	  datatype: "text",
	  error: ajaxQuoteError,
	  success: gotQuoteParameters,
	  timeout : 60000
	  });
}

function add() {
    if (Busy)
    {
        setTimeout('add()', 250);
    }
    else
    {
        var CurrentTab = $("#tabs").tabs('option', 'selected');
        if (TabConsistent(CurrentTab))
        {
            setBusy();
            Adding = true;
            $.ajax({
	          type: "POST",
	          url: "add.aspx",
	          data: 'NoProduct',
	          datatype: "text",
	          error: ajaxQuoteError,
	          success: gotQuoteParameters,
	          timeout : 60000
	          });
	    }
	    else
	    {
	        DisplayError(ConfigTabChangingErrorMessage);
	    }
	        
	}
}

function reset() {
    if (Busy)
    {
        setTimeout('reset()', 250);
    }
    else
    {
        var CurrentTab = $("#tabs").tabs('option', 'selected');
        
            setBusy();
            
            $.ajax({
	          type: "POST",
	          url: "resetProduct.aspx?position="+CurrentTab,
	          data: 'NoProduct',
	          datatype: "text",
	          error: ajaxQuoteError,
	          success: gotQuoteParameters,
	          timeout : 60000
	          });
	    
	        
	}
}

function gotQuoteParameters(json) {
	var tabPrefix = 'tabs-';
	//IE seems to dislike the line breaks, replacing them with javascript 
	//ones seems to do the trick.
	json = json.replace(String.fromCharCode(10), '\n');
	//Currently using the reference JSON parser.
	
	OK = true;
	
	try {
		quoteParameters = JSON.parse(json);
	}
	catch(error) {
		ready = true;
		$('#progress').dialog('close');
		DisplayError("Error getting quote data. "+json);
		OK = false;
	}
	if (OK)
	{
	    $('#myForm').empty();
        $('#myForm').append('<div id="tabs"><ul></ul></div>');
        NumberOfTabs = quoteParameters.tabs.length;
	    for (var tabCounter = 0; tabCounter < quoteParameters.tabs.length; tabCounter++) {
		    //Add the tab header. i.e. where to click.
		    $('#tabs ul').append('<li><a href="#tabs-' + tabCounter + '">' 
		      + quoteParameters.tabs[tabCounter].tabname + '</a></li>');
		    tabName = tabPrefix + tabCounter;
		    
		    var qtyCtl;
		    qtyCtl = '<div class="bpTab ui-tabs-hide" id="' + tabName 
		      + '"><div class="tabParams"><div class="tabqty">Quantity<input type="text" value="' 
		      + quoteParameters.tabs[tabCounter].quantity + '" class="bpGeneralQty"/></div>';
		    if (ConfigShowPrice)
		    {
		      qtyCtl += '<div class="tabPrice">'+ConfigPricePrefixText+ ": "+ quoteParameters.tabs[tabCounter].price + '</div>';
		    }		    
		    if (ConfigShowIPN)
		    {
		      qtyCtl += '<div class="ipn">'+ConfigIPNPrefixText+quoteParameters.tabs[tabCounter].IPN+'</div>';
		    }
		    qtyCtl += '</div>';
		    
		    //Add the tab and the quantity control
		    $('#tabs').append(qtyCtl);
	    }
	    //$('#bpGeneralQty').attr('value', quoteParameters.quoteConfig.Quantity);
    	
	    var quoteId = '12345';
    	
	    //$.get("QuoteItem.aspx?quote="+quoteId, gotJSON, "text");
	    $.ajax({
	      type: "GET",
	      url: "QuoteItem.aspx",
	      data: "quote="+quoteId,
	      datatype: "text",
	      error: ajaxQuoteError,
	      success: gotJSON,
	      timeout : 50000
	      });
	  }
}

function gotJSON(json) {
	//IE seems to dislike the line breaks, replacing them with javascript 
	//ones seems to do the trick.
	json = json.replace(String.fromCharCode(10), '\n');
	
	valid = true;
	
	try {
	    //Currently using the reference JSON parser.
		controls = JSON.parse(json);
	}
	catch(error) {
	    ready = true;
		$('#progress').dialog('close');
		DisplayError("Error getting initial quote values. "+json);
		valid = false;
	}
	
	if (valid)
	{
	    var generatedHtml = AddControlsToTabs(controls);

	    /*$(".combobox").combobox({
		    autoShow: false
		    $('.dropdownlistEdit').find('.dropdown').combobox($('.dropdownlistEdit').find('.selectbox'))

	    });*/
	    
	    //var dropdown = $('input.dropdown');
	    
	    
	    
	    /*$('.dropdown').each( 
        function()
        {
          $(this).combobox($(this).next());
        });
	    
	    $(dropdown).each( function () {
	      $(this).combobox(this.next());
	    });*/
	    
	    
	    bindEventHandlers();
	    /*$("div.bpControl select").bind("change",
	    function() {
		    sendUpdateJSON(generateUpdateJSON($(this).parent().get(0).id, this.options[this.selectedIndex].text));
	    });
	    $("div.bpControl input.value").bind("change",
	    function() {
		    sendUpdateJSON(generateUpdateJSON($(this).parent().get(0).id, this.value));
	    });*/
    }
    
    $(".numberEdit input").live("keydown",
    function(e) {
	    if (((e.keyCode >= 48) && (e.keyCode <= 57)) || ((e.keyCode >= 96) && (e.keyCode <= 105))) {
		    //number
	    }
	    else if ((e.keyCode >= 8) && (e.keyCode <= 46)) {
		    //delete or backspace
	    }
	    else if ((e.keyCode == 190) || (e.keyCode == 110)) {
		    //decimal point
		    if ($(this).attr('value').split('.').length > 1) {
			    e.preventDefault();
		    }
	    } else if (e.keyCode == 189) {
		    // - symbol
		    if ($(this).attr('value').split('-').length > 1) {
			    e.preventDefault();
		    }
		} else if (e.keyCode == 127) {
		  //iPhone Backspace for some odd reason.
	    } else {
		    //something else
		    e.preventDefault();
	    };
	});
	ShowAndHide();
	ready = true;
	$('#progress').dialog('close');
	$("#myForm").show("slide");
	SplitColumns();
	IeFix();
	clearBusy();
	if (Adding)
	{
	    $("#tabs").tabs('select', NumberOfTabs - 2);
	    Adding = false;
	}
	handleTabNext();
}

function ajaxQuoteError(XMLHttpRequest, textStatus, errorThrown)
{
    //Error with quote request.
    closePleaseWait();
    DisplayError("Problem with communication. Error was:\n"+textStatus +":"+errorThrown);
}

function saveAllowed()
{
    //iterate controls
    for(var counter = 0; counter < controls.length; counter++)
    {
        //look for error state
        if ( controls[counter].control.warnlevel == 2 )
        {
            return false;
        }
    }
    //return true if no error state
    return true;
}

function TabConsistent(Tab)
{
    if (ConfigForceTabConsistency)
    {
        //iterate controls
        for(var counter = 0; counter < controls.length; counter++)
        {
            //look for error state
            if (  (controls[counter].control.tab == Tab) && (controls[counter].control.warnlevel == 2) )
            {
                return false;
            }
        }
        //return true if no error state
        return true;
    }
    else
    {
        //if tab consistency is not required, always say that the tab is consistent.
        return true;
    }
}


//function reset()
//{
//    history.go(0);
//}

function AddNextTab()
{
   if (ConfigNextInsteadOfSave)
   {
       $('#bpSaveButton').after('<input type="button" value="Next" id="bpNextButton" class="ui-widget-content bpButton"/>');
//       $("#tabs").bind( "tabsselect", function(event, ui) {
//            handleTabNext();
//       });


       
       
       //$("#tabs ul li a").click(handleTabNext);
       
       $("#bpNextButton").click(NextPressed);
   }    
}


function handleTabNext()
{
    if (ConfigNextInsteadOfSave)
    {
        var CurrentTab = $("#tabs").tabs('option', 'selected');
        if (CurrentTab == NumberOfTabs -1)
        {
            //on the last tab.
            $("#bpSaveButton").css('display', '');
            $("#bpNextButton").css('display', 'none');
        }
        else
        {
            $("#bpNextButton").css('display', '' );
            $("#bpSaveButton").css('display', 'none');
        }
    }
    
}

function NextPressed()
{
    if(Busy)
    {
        //wait and retry.
        setTimeout("NextPressed()", 250);
    }
    else
    {    
        CurrentTab = $("#tabs").tabs('option', 'selected');
        if (TabConsistent(CurrentTab))
        {
            $("#tabs").tabs('select', CurrentTab + 1);
            handleTabNext();
        }
        else
        {
            DisplayError(ConfigTabChangingErrorMessage);
        }
    }
}

function save() 
{
    log('Save Start');
    if (Busy)
    {
        OutstandingSave = true;
    }
    else
    {            
        //Check Save is allowed display error if not
        if (saveAllowed())
        {    
            $('#bpSaveButton').attr('disabled', 'disabled');
            $('#bpCancelButton').attr('disabled', 'disabled');
            displayPleaseWait();
            DisableUpdate = false;
            ready = false;
            $.get("Save.aspx", saved, "text");
        } else
        {
            DisplayError("You must select a consistent set of options.");
        }
    }
}

function cancel()
{
    $('#bpSaveButton').attr('disabled', 'disabled');
    $('#bpCancelButton').attr('disabled', 'disabled');
    //displayPleaseWait();
    DisableUpdate = false;
    ready = false;
    $.get("Cancel.aspx", cancelled, "text");
}

function saved(json)
{
    var result = JSON.parse(json);
    if (result.Saved == "true")
    {
        //closePleaseWait();
        $("#myForm").hide("slide");
        //DisplayError("Saved");
        log('Saved Nearly Finished');
        if (ConfigDontBreakOutOfIFrame)
        {
            if (result.MoveTo != undefined)
            {
                window.location = result.MoveTo;
            }
            else
            {
                window.location = "Return.aspx";         
            }
        }
        else
        {
            if (result.MoveTo != undefined)
            {
                window.top.parent.location = result.MoveTo;
            }
            else
            {
                window.top.parent.location = "Return.aspx";         
            }
        }
    }
    else
    {
        DisplayError(result.Error);
    }
}

function cancelled(json)
{
    var result;
    result = JSON.parse(json);
    closePleaseWait();
    $("#myForm").hide("slide");
    window.top.parent.location = "Return.aspx";         
}

function DisplayError(error)
{
  $("#dialog").dialog('destroy');
  $("#dialog").text(error);
  $("#dialog").dialog({open: true, modal:true, buttons: { "Ok": function() { $(this).dialog("close"); }}})
}

function checkValid(thisCtl)
{
    var text;
    var max = $(thisCtl).parent().find('.max').text();
    var min = $(thisCtl).parent().find('.min').text();
    var orig = $(thisCtl).parent().find('.origValue').text();
    text = $(thisCtl).val();
    var value = parseInt(text);
    
    if ((!isNaN(value)) && (!isNaN(parseInt(min))) && (!isNaN(parseInt(max))))
    {
        if (value > max)
        {
            DisplayError('Value: '+ $(thisCtl).val() + ' is greater than the maximum of '+ max); 
            $(thisCtl).val(orig);  
            return false;  
        }
        if (value < min)
        {
            DisplayError('Value: '+ $(thisCtl).val() + ' is less than the minimum of '+ min);
            $(thisCtl).val(orig); 
            return false;
        }
        return true;
    }
    else
    {
        return true;
    }
}

function setBusy()
{
    $('#myForm').addClass("progress");
    Busy = true;
    //$('#bpSaveButton').attr('disabled', true);
    //$('#bpCancelButton').attr('disabled', true);
}

function clearBusy()
{
    $('#myForm').removeClass("progress");
    $('#bpSaveButton').removeAttr('disabled');
    $('#bpCancelButton').removeAttr('disabled');
    Busy = false;
    if (OutstandingSave)
    {
        OutstandingSave = false;
        log('processing outstanding save')
        save();
    }
}

function bindEventHandlers()
{
	$("div.bpControl select").unbind("change");
	$("div.bpControl select").bind("change",
	function() {
	    if ( !DisableUpdate)
	    {   
		    setBusy();
		    if ( $(this).parent().get(0).id != '')
		    {    
		        sendUpdateJSON(generateUpdateJSON($(this).parent().get(0).id, this.options[this.selectedIndex].text));
		    } 
		    else
		    {
		        sendUpdateJSON(generateUpdateJSON($(this).parent().parent().get(0).id, this.options[this.selectedIndex].text));  
		    }
		}
	});
	$("div.bpControl:not(.checkboxEdit) .value:not(.selectbox)").unbind("change");
	
	$("div.bpControl:not(.checkboxEdit) .value:not(.selectbox)").bind("change",
	function() {
	    if ( !DisableUpdate)
	    {        
		    setBusy();
		    if ( $(this).parent().get(0).id != '')
		    {
		        if (checkValid(this))
	            {	
		            sendUpdateJSON(generateUpdateJSON($(this).parent().get(0).id, this.value));
		        }
		    }
		    else
		    {
		        if (checkValid($(this).parent()))
		        {
		            sendUpdateJSON(generateUpdateJSON($(this).parent().parent().get(0).id, this.value));
		        }
		    }
		        
		}
	});
	
	
	$("div.bpControl.checkboxEdit .value").unbind("click");
	
	$("div.bpControl.checkboxEdit .value").bind("click",
	function() {
	    if ( !DisableUpdate)
	    {        
		    setBusy();
		    if ( $(this).parent().get(0).id != '')
		    {
		        if (checkValid(this))
	            {	
		            sendUpdateJSON(generateUpdateJSON($(this).parent().get(0).id, this.checked));
		        }
		    }
		    else
		    {
		        if (checkValid($(this).parent()))
		        {
		            sendUpdateJSON(generateUpdateJSON($(this).parent().parent().get(0).id, this.checked));
		        }
		    }
		        
		}
	});
	
	
	
	 $("input, div.bpControl .quantity").live("keydown",
         function(e) {
             if ( DisableUpdate)
             {
	             e.preventDefault();
	         }
	     });
	
	$("div.bpControl .quantity").unbind("change");
	$("div.bpControl .quantity").bind("change",
	function() {
	    log('Qty Change');
	    if ( !DisableUpdate)
	    {
		    setBusy();
		    sendUpdateJSON(generateQtyUpdateJSON($(this).parent().parent().get(0).id, this.value));
		}
	});
	
	$(".tabqty input").unbind("change");
	$(".tabqty input").bind("change",
	function() {
	    log('qty change');
	    if ( !DisableUpdate)
	    {
		    setBusy();
		    sendUpdateJSON(generateTabQtyUpdateJSON($(this).parent().parent().parent().get(0).id, this.value));
		}
	});
	
	
	$("div.bpControl .warning").bind( "click",
	function () {
	  DisplayError($(this).contents(".warningtext").text());
	});
	
	try
	{
	    //if (jQuery.isFunction(jQuery.combobox))
	    //{
	      $('.dropdownedit').each( 
          function()
          {
            $(this).combobox($(this).prev());
          });
	    //}
	} catch (err)
	{    //bury the error for now - we don't want to break because of missing combobox handling.
	  alert('error');
	}
	$(".dateEdit input").datepicker({changeMonth: true,	changeYear: true, dateFormat: "dd/mm/yy"});
        //$(".dateEdit input").datepicker();
	
   $('.value').unbind( "focus");
   $('.value').bind( "focus", function() {
        currentFocus = jQuery(this).parent()[0].id;
    });
}

function gotUpdateJSON(json) {
	//IE seems to dislike the line breaks, replacing them with javascript 
	//ones seems to do the trick.
	json = json.replace(String.fromCharCode(10), '\n');
	
	valid = true;
	
	//Currently using the reference JSON parser.
	try
	{
	  var updateControls = JSON.parse(json);
	}
	catch(error)
	{
	  valid=false;
	  closePleaseWait();
	  DisplayError("Error in Update Command: " + json);
	  //alert("Error in update commmand.");
	}

    if (valid)
    {
	    DisableUpdate = true;
	    
	    if ((updateControls.length === undefined) && (updateControls !=undefined))
	    {
	        //This means that the updateControl is only updating one control and an 
	        //array with one item doesn't work under javascript
        	if(updateControls.quoteid != undefined)
        	{
        	    //This is a tab update.
        	    //For Each 'tab' do
                for (var tabCounter = 0; tabCounter < updateControls.tabs.length; tabCounter++)
                {
                    //find tab html
                    var tabName = '#tabs-'+tabCounter;
                    if (ConfigShowPrice)
                    {
                      $(tabName + ' .tabPrice').text(ConfigPricePrefixText+ ": " + updateControls.tabs[tabCounter].price);
                    }      

                    if (ConfigShowIPN)
                    {
                      $(tabName + ' .ipn').text(updateControls.tabs[tabCounter].IPN);
                    }
                }
        	}
        	else
        	{
        	
        	    var found = false;
	            for (var counter = 0;
	            (!found) && (counter < controls.length); counter++) {
		            //
		            if (controls[counter].control.id === undefined) {
			            alert('Undefined id on update control.');
		            }
		            else {
			            if (controls[counter].control.id == updateControls.control.id) {
				            var htmlId;
				            var controlHtml;				        
				            controls[counter].control = updateControls.control;
				            controlHtml = renderGenericControl(controls[counter].control);
				            htmlId = '#ctl' + controls[counter].control.id;
				            $(htmlId).replaceWith(controlHtml);
				            found = true;
			            }
		            }
	            }
	        }
	    }
	    else
	    {   
	        for (var updateObjectCounter = 0; updateObjectCounter < updateControls.length; updateObjectCounter++) {
		        //Each update object, look for it in the main list of controls, and update it. Then draw it.
		        //Currently looping through the list of controls, not ideal. 
		        //Probably to be replaced with something more efficient later.
		        var found = false;
		        for (var counter = 0;
		        (!found) && (counter < controls.length); counter++) {
			        //
			        if (controls[counter].control.id === undefined) {
				        alert('Undefined id on update control.');
			        }
			        else {
				        if (controls[counter].control.id == updateControls[updateObjectCounter].control.id) {
					        var htmlId;
					        var controlHtml;
					        controls[counter].control = updateControls[updateObjectCounter].control;
					        controlHtml = renderGenericControl(controls[counter].control);
					        htmlId = '#ctl' + controls[counter].control.id;
					        $(htmlId).replaceWith(controlHtml);
					        found = true;
				        }
			        }
		        }
		    }
	    }
        bindEventHandlers();
        DisableUpdate = false;
	    $("#tabs").tabs();
//	    $("#tabs").tabs({select: function(event, ui)
//        {
//            var CurrentTab = $("#tabs").tabs('option', 'selected');
//            if (TabConsistent(CurrentTab))
//            {
//                setTimeout('handleTabNext()', 250);
//                return true;
//            }
//            else
//            {
//                DisplayError(ConfigTabChangingErrorMessage);
//                return false;
//            }
//        }});
	    $("#tabs").bind('tabsselect', function(event, ui){
           ChangeTab(ui.index);
           return false; //Always disallow changing directly - rely on the function below to change tabs.
         });
	    closePleaseWait();
	    SplitColumns();
	    clearBusy();
	    
	    ShowAndHide();
	    //$(".dateEdit").datepicker({dateFormat: "dd/mm/yyyy"});
            $(".dateEdit input").datepicker("destroy");
            $(".dateEdit input").datepicker({changeMonth: true,	changeYear: true, dateFormat: "dd/mm/yy"});

            returnFocus();

            IeFix();
	   
	    $.ajax({
	      type: "POST",
	      url: "UpdateQuote.aspx",
	      data: "",
	      datatype: "text",
	      error: ajaxQuoteError,
	      success: gotUpdateProductJSON,
	      timeout : 60000
	    });
	    
	}
}

function gotUpdateProductJSON(json) {
    var OK = true;
    try
    {
      json = JSON.parse(json);
    }
    catch (error)
    {
      OK = false;
    }
    if (OK)
    {
        //For Each 'tab' do
        for (var tabCounter = 0; tabCounter < json.tabs.length; tabCounter++)
        {
          //find tab html
          var tabName = '#tabs-'+tabCounter;
          if (ConfigShowPrice)
	      {
	          $(tabName + ' .tabPrice').text(ConfigPricePrefixText+ ": " + json.tabs[tabCounter].price);
	      }      
          
          if (ConfigShowIPN)
          {
              $(tabName + ' .ipn').text(json.tabs[tabCounter].IPN);
          }
          //Update Quantity
          
          //Update Price
        //end
        }
    }
    clearBusy();
    returnFocus();

}

function sendUpdateJSON(update) {
	
    $.ajax({
	  type: "POST",
	  url: "Update.aspx",
	  data: update,
	  datatype: "text",
	  error: ajaxQuoteError,
	  success: gotUpdateJSON,
	  timeout : 60000
	  });
	//displayPleaseWait();
}

function generateUpdateJSON(controlId, newValue) {
    var control = controlId.substring(3);
	var updateJSON;
//	if (controls[control].type='checkbox')
//	{
//	    if (newValue == "on")
//	    {
//	        updateJSON = '{\n  "id": "' + control + '";\n  "value": "true"; \n';
//	    } else
//	    {
//	        updateJSON = '{\n  "id": "' + control + '";\n  "value": "false"; \n';
//	    }
//	}else 
//	{
	    updateJSON = '{\n  "id": "' + control + '";\n  "value": "' + escapeQuotes(newValue)+'"; \n';
//	}
	if (controls[control].control.hasqty)
	{
	    updateJSON +=  '"quantity": "' + controls[control].control.quantity + '"\n';   
	}
	updateJSON += '\n}\n';
	return updateJSON;
}

function generateQtyUpdateJSON(controlId, qty) {
    var control = controlId.substring(3);
	var updateJSON = '{\n  "id": "' + control + '";\n  "value": "' + escapeQuotes(controls[control].control.value)+'"; \n';
	if (controls[control].control.hasqty)
	{
	    updateJSON +=  '"quantity": "' + qty + '"\n';
	}
	updateJSON += '\n}\n';
	return updateJSON;
}

function generateTabQtyUpdateJSON(controlId, qty) {
/*   {"product": {' + crlf +
    '"id": "' + IntToStr(id) + '",' + crlf +
    '"tab": "' + IntToStr(tab) + '",' + crlf +
    '"quantity": "' + IntToStr(Quantity) + '",' + crlf +
    '"group": "' + IntToStr(Group) + '",' + crlf +
    '"enabled": "' + BooleanToStr(Enabled) + '"' + crlf +
    '}}';
*/

    var control = controlId.substring(5);
	var updateJSON = '{"product": {\n  "index": "' + control + '",\n  "quantity": "' 
	    + qty +'" \n';
	updateJSON += '\n}}\n';
	return updateJSON;
}

function renderGenericControl(control) {
	var result = '';
	switch (control.type) {
	case 'textedit':
		result = renderTextedit(control);
		break;
	case 'dropdown':
		result = renderDropDown(control);
		break;
	case 'numberedit':
		result = renderNumberedit(control);
		break;
	case 'dropdownlist':
		result = renderDropDownList(control);
		break;
	case 'divider':
	    result = renderDivider(control);
		break;
    case 'checkbox':
	    result = renderCheckbox(control);
		break;
	case 'dateedit':
	    result = renderDateedit(control);
		break;
	default:
		result = renderOther(control);
		break;
	}
	return result;
}

function AddControlsToTabs(values) {
	var result = "";
	var tabs;
	var tabPrefix = 'tabs-';
	var tabName;

	for (var counter = 0; counter < values.length; counter++) {
		tabName = tabPrefix + values[counter].control.tab;
		var tabLabel;
		$('#' + tabName).append(renderGenericControl(values[counter].control));
	}
	$("#tabs").tabs();
	$("#tabs").bind('tabsselect', function(event, ui){
           ChangeTab(ui.index);
           return false; //Always disallow changing directly - rely on the function below to change tabs.
         });
	
	return result;
}

function ChangeTab(To)
{
    if(Busy)
    {
        setTimeout("ChangeTab("+To+")", 250);
    }
    else
    {
       var CurrentTab = $("#tabs").tabs('option', 'selected');
       if (CurrentTab != To) //if changing to the same tab, do nothing.
       {
           if ( TabConsistent(CurrentTab) )
           {
               $("#tabs").unbind('tabsselect');
               $("#tabs").tabs("select", To);
               $("#tabs").bind('tabsselect', function(event, ui){
                 ChangeTab(ui.index);
                 return false; //Always disallow changing directly - rely on the function below to change tabs.
                });
               setTimeout('handleTabNext()', 250);
           }
           else
           {
               DisplayError(ConfigTabChangingErrorMessage);
           }
       }
           
    }
} 

function ShowAndHide()
{
  $('.bpControl.invisible').hide();
  $('.bpControl not(.invisible)').show();
}

function SplitColumns ()
{ 
  if (ConfigColumns == 2)
  { 
      $('#tabs >[id^=tab]').each(
        function() 
        { 
          try
          {
            var ctlCount; 
            var offset;
            var middleControl;
            
            if(typeof(ConfigMiddleControl) != 'undefined')
            {
                middleControl = $($(this).children('div')[ConfigMiddleControl]);
            }
            else
            {    
                ctlCount = ((Math.round($(this).children('div').length-2) / 2));
                middleControl = $($(this).children('div')[Math.floor(($(this).children('div').length) / 2)]); 
            }
            $(middleControl).nextAll('div').each( function(i) {
              var ctlTop = ((i+1) * ConfigCtlHeight)+12;
              $(this).addClass('RightColumn');
              $(this).css('position', 'absolute').css('top', ctlTop + 'px');
            });
            
            $('#tabs >[id^=tab]').each(
            function() 
            {
                $(this).children('div').width('0px').css('padding-left', '0px').css('padding-right', '0px').css('border-left', '0px').css('border-right', '0px');
                $("div.tabParams").width('');
            });
          }
          catch (err)
          {
            alert(err.message);
          }    
        });
    } else if (ConfigColumns == 1)
  {
      $('#tabs >[id^=tab]').each(
        function() {
            try {
                /*$(this).children('div.:not(:last)..:not(:first)').css('border-bottom', 'solid 1px LightSteelBlue');*/
                /*styling code doesn't really belong here. */


                $(this).children('div').width('0px');
                //$(this).children('div').width(ConfigColumnWidth);
                $(this).children('div').css('padding-right', '0');
                $(this).children('div').css('padding-left', '0');
                $(this).children('div').css('margin-right', '50px');
                $("div.tabParams").width('');
            }
            catch (err) {
                alert(err.message);
            }
        });
    }
}

function IeFix()
{
    /*
    //if there is no browser detection (possible to happen in future - add in).
    if (!jQuery.browser) 
    {
        (function($) {
            var userAgent = navigator.userAgent.toLowerCase();
            $.browser = {
                version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],               
                msie: /msie/.test( userAgent ) && !/opera/.test( userAgent )
            };
        })(jQuery);
    }
    
    if (ConfigAlwaysResetOrder || ($.browser.msie && ($.browser.version < 8.0)))
    {
        //This seems to sort out the z-index issue when applied to IE7 and hopefully IE6
        $(function() {
	        var zIndexNumber = 1000;
    	    $('div.bpControl').each(function() {
	    	    $(this).css('zIndex', zIndexNumber);
		        zIndexNumber -= 10;
	        });
        });
        //Reset this to the top of the pile regardless.
        $('#bpGeneralParams').css('zIndex', 10000);
    };
    */
}

function AlertIfOldIE()
{
  /*engine = null;
  if (window.navigator.appName == "Microsoft Internet Explorer")
  {
   // This is an IE browser. What mode is the engine in?
   if (document.documentMode) // IE8
      engine = document.documentMode;
   else // IE 5-7
   {
      engine = 5; // Assume quirks mode unless proven otherwise
      if (document.compatMode)
      {
         if (document.compatMode == "CSS1Compat")
            engine = 7; // standards mode
        }
     }
     // the engine variable now contains the document compatibility mode.
  if(engine < 8)
  {     
    DisplayError("Please be aware that you are either using an old, unsupported browser, or you have IE8 Compatibility mode turned on.");
  }
  }
  */
}
