/* (c) 2008 Intelligent Environments Group plc. All rights reserved */

function showObject(objID){document.getElementById(objID).style.display='block';}
function hideObject(objID){document.getElementById(objID).style.display='none';}
function MM_goToURL(){var i,args=MM_goToURL.arguments;document.MM_returnValue=false;for(i=0;i<(args.length-1);i+=2)eval(args[i]+".location='"+args[i+1]+"'");}
function get_random()
{var ranNum=Math.floor(Math.random()*5);return ranNum;}
var whichImg=get_random();function show_image(){var img=new Array(5)
img[0]="<img src='../../../../assets/brand/BrandCore/graphics/logos/1.jpg' alt='' /> ";img[1]="<img src='../../../../assets/brand/BrandCore/graphics/logos/2.jpg' alt='' />";img[2]="<img src='../../../../assets/brand/BrandCore/graphics/logos/3.jpg' alt='' />";img[3]="<img src='../../../../assets/brand/BrandCore/graphics/logos/4.jpg' alt='' />";img[4]="<img src='../../../../assets/brand/BrandCore/graphics/logos/5.jpg' alt='' />";document.write(img[whichImg]);}
function doSaveAs() { if (document.execCommand) { document.execCommand("SaveAs") } }

/* Test */

function transferToChanged() {
    var Proxy = new serviceProxy("/ClientServices/ClientData.svc/");
    Proxy.invoke("GetAccountList", { "action": "JsonAction", "submit": [{ "Key": "data:SelectedValue1", "Value": $("select#selectedindex_ebafde01-85d2-4892-8bda-b3566f9b34e7").val()}], "retrieve": "MyCollectionListB:." }, function(result) {
        var options = "";

        for (var i = 0; i < result.length; i++) {

            options += '<option value="' + result[i].Key + '">' + result[i].Value + '</option>';
        }
        $("select#selectedindex_c22757fc-9526-45c4-972b-0d78e3cd8b85").html(options);


    });
}


function dropdownchanged() {
    alert('dropdownchanged');
}

// *** Service Calling Proxy Class
function serviceProxy(serviceUrl, itemId) {
    var _I = this;
    this.serviceUrl = serviceUrl;
    // *** Call a wrapped object
    this.invoke = function(method, data, callback, error, bare) {
        // *** Convert input data into JSON - REQUIRES Json2.js        
        var json = JSON2.stringify(data);
        // *** The service endpoint URL
        var url = _I.serviceUrl + method;
        jQuery.ajax({
            beforeSend: function(XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("itemId", itemId);
            },
            url: url,
            data: json,
            type: "POST",
            processData: false,
            contentType: "application/json",

            timeout: 10000,
            dataType: "text",  // not "json" we'll parse                    
            success:

  function(res) {
      if (!callback) return;

      // *** Use json library so we can fix up MS AJAX dates
      var result = JSON2.parse(res);

      // *** Bare message IS result                        
      if (bare) {
          callback(result); return;
      }
      // *** Wrapped message contains top level object node
      // *** strip it off
      for (var property in result) {
          callback(result[property]);
          break;
      }
  },
            error:
                        function(xhr, textStatus, errorThrown) {
                            if (!error) {
                                return;
                            }

                            if (textStatus == 'timeout') {
                                error({ Message: "Unknown server error." }, textStatus)
                            }

                            if (xhr.responseText) {
                                if (JSON2) {
                                    var err = JSON2.parse(xhr.responseText);
                                    if (err) {
                                        error(err, textStatus);
                                    }
                                    else {
                                        error({ Message: "Unknown server error." }, textStatus)
                                    }
                                }
                                else {
                                    error({ Message: "Unknown server error." }, textStatus)
                                }
                            }
                            else {
                                error({ Message: "Unknown server error." }, textStatus)
                            }
                            return;
                        }
        });
    }
}

function SubmitForm(obj) {
    if (obj.form.Transactional1.name == "") {
        obj.form.Transactional1.name = obj.name;
        obj.form.submit();
    }
    else {
        return false;
    }
}

function SliderCallback() {
    var theButton = document.getElementById('Target_8364bd13-6b90-4669-94b6-7f2ae1b4bd1e');
    theButton.click();
}

function cascadingDropDownSelectionChanged(itemId, itemName, targetItemName, serviceUrl, serviceMethod, uiAction, inputFieldPath, parameters, returnFieldPath, initialSelection, loadingText, errorText) {

    var selectedItem = $("select#" + itemName).val();
    if (selectedItem != "") {
        var Proxy = new serviceProxy(serviceUrl, itemId);

        var waitMessage = "";
        waitMessage += '<option value="">' + loadingText + '</option>';
        $("select#" + targetItemName).html(waitMessage);

        Proxy.invoke(serviceMethod, {
            "action": uiAction,
            "submit": [{ "Key": inputFieldPath, "Value": $("select#" + itemName).val()}],
            "retrieve": returnFieldPath
        },
		    function(result) {
		        var options = "";
		        if (result.length > 0) {
		            options += '<option value="">' + initialSelection + '</option>';
		            for (var i = 0; i < result.length; i++) {

		                options += '<option value="' + result[i].Key + '">' + result[i].Value + '</option>';
		            }
		        }
		        else {
		            options += '<option value="">' + errorText + '</option>';
		        }

		        $("select#" + targetItemName).html(options);
		    }
	    );
    }
    else {
        var options = "";
        options += '<option value="">' + initialSelection + '</option>';
        $("select#" + targetItemName).html(options);
    }
}

function recalculateLoanDetails(itemId, controlId, serviceUrl, serviceMethod, uiAction, inputFieldPath, returnFieldPath, errorMessage, errorPage) {

    if (jQuery('#displayResults').is(':visible') == true) {
        showLoading('#displayResults');
    }
    else if (jQuery('#displayInstructions').is(':visible') == true) {
        showLoading('#displayInstructions');
    }
    else if (jQuery('#displayError').is(':visible') == true) {
        showLoading('#displayError');
    }


    var Proxy = new serviceProxy(serviceUrl, itemId);
    Proxy.invoke(serviceMethod, {
        "action": uiAction,
        "submit": [{ "Key": inputFieldPath, "Value": jQuery('#' + controlId).val()}],
        "retrieve": returnFieldPath
    },
    function(result) {
        var response = JSON2.parse(result);

        if (!response.IsError) {

            var calcResults = JSON2.parse(response.ReturnValue);

            jQuery('#loanAmount').html(formatCurrency(calcResults.Results[0].LoanPrincipalAmount, true));
            jQuery('#monthlyRepayment').html(formatCurrency(calcResults.Results[0].MonthlyPaymentAmount));
            jQuery('#apr').html(calcResults.Results[0].APR.toFixed(1) + '%');
            jQuery('#loanTerm').html(calcResults.Results[0].NumberOfPayments + ' months');
            jQuery('#totalPayable').html(formatCurrency(calcResults.Results[0].TotalAmountPayable));

            jQuery('#displayResults').show();
            jQuery('#displayInstructions').hide();
            jQuery('#displayError').hide();
        }
        else {
            // FaultCode 1 => SessionTimeout
            if (response.Errors[0].FaultCode == 1) {
                // Reloading the page will cause a full request to the server
                // Our regular session expiry code will kick in and redirect the user to the appropriate session expiry page
                window.location.reload();
            }
            // FaultCode 2 => ServiceTimeout
            else if (response.Errors[0].FaultCode == 2) {
                jQuery('#displayResults').hide();
                jQuery('#displayInstructions').hide();
                jQuery('#displayError').html(errorMessage);
                jQuery('#displayError').show();
            }
            else {
                window.location = errorPage;
            }
        }

        hideLoading();
    },
    function(err, textStatus) {
        if (textStatus == 'timeout') {
            hideLoading();
            jQuery('#displayResults').hide();
            jQuery('#displayInstructions').hide();
            jQuery('#displayError').html(errorMessage);
            jQuery('#displayError').show();
        }
        else {
            window.location = errorPage;
        }
    }
    );
}

function formatCurrency(num, integerValue) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    }

    return (((sign) ? '' : '-') + '&pound;' + num + ((integerValue) ? '' : '.' + cents));
}

function showLoading(selector) {
    var options = {
        loadSpeed: 'slow',
        closeSpeed: 'fast',

        zIndex: 998,
        opacity: 0.5,

        color: '#F2F9EB',

        image: {
            src: '/assets/shared/graphics/ajax-loader.gif',
            alt: 'loading...',

            size: {
                width: 100,
                height: 10
            }
        }
    };

    jQuery(selector).loadAnimation(options);
}

function hideLoading() {
    jQuery.loadAnimation.end();
}
