﻿//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;

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 closePleaseWait()
{
    $('#progress').dialog('close');
    $('#progress').dialog('destroy');
    //$("#myForm").show("", {}, 500);
    //$("#myForm input").removeAttr("readonly", "readonly");
    //alert(this);
    //$(currentFocus).focus();
    //refocus
}

function readyToGo() {
   
    $(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();
    
    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 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 initial quote parameters. "+json);
		OK = false;
	}
	if (OK)
	{
	    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" 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();
}

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 save() 
{
    
    //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");
        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");
    $('#bpSaveButton').attr('disabled', true);
    $('#bpCancelButton').attr('disabled', true);
}

function clearBusy()
{
    $('#myForm').removeClass("progress");
    $('#bpSaveButton').removeAttr('disabled');
    $('#bpCancelButton').removeAttr('disabled');
}

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() {
	    if ( !DisableUpdate)
	    {
		    setBusy();
		    sendUpdateJSON(generateQtyUpdateJSON($(this).parent().parent().get(0).id, this.value));
		}
	});
	
	$(".tabqty input").unbind("change");
	$(".tabqty input").bind("change",
	function() {
	    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"});
	
//   $('.value').unbind( "focus");
//   $('.value').bind( "focus", function() {
//        currentFocus = this;
//    });
}

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();
	    closePleaseWait();
	    SplitColumns();
	    clearBusy();
	    
	    ShowAndHide();
	    //$(".dateEdit").datepicker({dateFormat: "dd/mm/yyyy"});
	    
	   
	    $.ajax({
	      type: "POST",
	      url: "UpdateQuote.aspx",
	      data: "",
	      datatype: "text",
	      error: ajaxQuoteError,
	      success: gotUpdateProductJSON,
	      timeout : 10000
	    });
	    
	}
}

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
        }
    }

}

function sendUpdateJSON(update) {
	
    $.ajax({
	  type: "POST",
	  url: "Update.aspx",
	  data: update,
	  datatype: "text",
	  error: ajaxQuoteError,
	  success: gotUpdateJSON,
	  timeout : 10000
	  });
	//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([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();
	return result;
}

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;
            
            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)+20;
              $(this).css('left', '635px').css('position', 'absolute').css('top', ctlTop + 'px');
            });
            $(middleControl).nextAll('div.:not(:last)').css('border-bottom', 'solid 1px LightSteelBlue');
            $(middleControl).nextAll('div.:not(:first)').css('border-top', 'solid 1px LightSteelBlue');
            $(middleControl).css('border-top', 'solid 1px LightSteelBlue');
            $(middleControl).prevAll('.bpControl.:not(:last)').css('border-bottom', 'solid 1px LightSteelBlue');
            $(middleControl).prevAll('.bpControl.:not(:last)').css('border-top', 'solid 1px LightSteelBlue');
            
            $(middleControl).prevAll('.bpControl.:last').css('border-top', 'solid 1px gray ');
            
            //$(middleControl).css('background-color', 'red');
          } 
          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');
            $(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');
          } 
          catch (err)
          {
            alert(err.message);
          }    
        });
    }
}

