var intLimitPost = 0; // set postal or collection limit

//******************************************************

function toggleDiv(strShow) { 
    if ($("#" + strShow).css("display") == "none") {
        $("#" + strShow).show();
    } else {
        $("#" + strShow).hide();
    } 
}

//******************************************************

function replaceImage(imgID, imgNew) {
    $('#' + imgID).attr('src', imgNew);
}

function addSaturdayDelivery() {
    var dblTotal = 0;
    if ($('#saturday:checked').val() == 1) {
        dblSaturday = 2;
        $('#saturdayCost').val('2');
        $('#saturdayCostDisplay').html('&pound;2.00');
    }
    else {
        dblSaturday = 0;
        $('#saturdayCost').val('0');
        $('#saturdayCostDisplay').html('&pound;0.00');
    }
    $('#totalCost').html('<strong>&pound;' + (dblCurrency + dblSaturday + dblCash + dblPostage).toFixed(2) + '</strong>');
}

function addCashBank() {
    var dblTotal = 0;
    if ($('#cashBank:checked').val() == 1) {
        dblCash = Number((dblCurrency * .005).toFixed(2));
        $('#cashBankCost').val(dblCash);
        $('#cashBankDisplay').html('&pound;' + dblCash);
		
    }
    else {
        $('#cashBankCost').val('0');
        $('#cashBankDisplay').html('&pound;0.00');
        dblCash = 0;
    }
    $('#totalCost').html('<strong>&pound;' + (dblCurrency + dblSaturday + dblCash + dblPostage).toFixed(2) + '</strong>');
}

function IsNumeric(sText)

{
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;


    for (i = 0; i < sText.length && IsNumber == true; i++) 
    { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
    }
    return IsNumber;
   
}

var dblMinValue = 100; // minimum amount of sterling to order
var dmlMaxValue = 2500; // max currency

var intCollectionCurrencies	= 1;

function checkValues(intID) {
	
    var dblSterling = $("#sterling" + intID).val();
    if (dblSterling > dmlMaxValue || dblSterling < dblMinValue) {
        alert("This service requires a minimum of \u00A3" + dblMinValue + " up to \u00A3" + dmlMaxValue);
        $("#sterling" + intID).val(0);
        return false;
    }
    else {
        return true;	
    }
}

function removeID(strID) {
    $('#' + strID).hide('slow').remove();	
    collectionTotal();
}

function addCollectionCurrency(intType) {
    intCollectionCurrencies++;
    doJqueryAjax('mailNothing', '', 'op=addcurrency&optionvalue=' + intCollectionCurrencies + '&optionextra=' + intType, 'GET', '');
}

function collectionChange(intID, intType) {
	
    var dblResult = 0;
	
    var dblSterling 		= $("#sterling" + intID).val();
    var dblCurrency 		= $("#amount" + intID).val();
    var dblDenomination 	= $("#currency" + intID).val();
	
	
    switch (intType) {
        case 0:
        case 1:
            if (IsNumeric(dblCurrency)) {
                
                dblResult = Number(parseFloat(dblCurrency)) / (arrCurrencies[dblDenomination]['exchange'] * ((100 - arrCurrencies[dblDenomination]['sell']) / 100));
                if (dblResult > dmlMaxValue) {
                    alert("This service requires a minimum of \u00A3" + dblMinValue + " up to \u00A3" + dmlMaxValue);
                    $("#amount" + intID).val(0);
                }
                else {
                    if (isNaN(dblResult)) {
                        $("#sterling" + intID).val(0);
                    }
                    else {
                        $("#sterling" + intID).val( dblResult.toFixed(2) );
                    }
                }
            }
            else {
                $("#amount" + intID).val(0);
            }
            break;
		
        case 2:
            if (dblSterling == '') {
                $("#sterling" + intID).val(0);
            } else if (IsNumeric(dblSterling)) {
                dblResult = Number(parseFloat(dblSterling)) * (arrCurrencies[dblDenomination]["exchange"] * ((100 - arrCurrencies[dblDenomination]["sell"]) / 100));
                $("#amount" + intID).val( dblResult.toFixed(2) );
            }
            else {
                $("#sterling" + intID).val(0);
            }
            break;
		
    } // end switch
	
    // total
    collectionTotal();
	
}

/*
 * total of all items in basket
 */
 
function collectionTotal() {
	
    var dblTotal				= 0;
    var intLimit				= 0;
    var strLimit				= '';
	
    $('.currencyItem').each(
        function() {
            if (!isNaN($(this).val())) {
                dblTotal		+= parseFloat($(this).val());
            }
        }
        );
	
    if (intLimitPost > 0) {
        if (dblTotal > intLimitPost) {
            intLimit = 1;
            $('#collectionTotal').css('color', '#a00');
            strLimit = 'Above max limit: ';
        }
    }
	
    $('#collectionTotal').html(strLimit + '&pound;' + dblTotal.toFixed(2));
	
    if (dblTotal > 0 && intLimit == 0) {
        $('#collectionSubmit').show('slow');
        $('#collectionTotal').css('color', '#0a0');
		
    }
    else {
        $('#collectionSubmit').hide('slow');
    }
}

/*
 *
 */
 
function getCurrency(intID, intCurrency) {
    var dblResult = 0;
	
    var dblSterling = $("#sterling" + intID).val();
    var dblCurrency = $("#currency" + intID).val();
	
    if (dblSterling > dmlMaxValue) {
        alert("This service requires a minimum of \u00A3" + dblMinValue + " up to \u00A3" + dmlMaxValue);
        $("#sterling" + intID).val(0);
    }
    else {
        switch (intCurrency) {
            case 1:
                if (IsNumeric(dblCurrency)) {
                    dblResult = Number(parseInt(dblCurrency)) / (arrCurrencies[intID]['exchange'] * ((100 - arrCurrencies[intID]['sell']) / 100));
                    if (dblResult > dmlMaxValue) {
                        alert("This service requires a minimum of \u00A3" + dblMinValue + " up to \u00A3" + dmlMaxValue);
                        $("#currency" + intID).val(0);
                    }
                    else {
                        $("#sterling" + intID).val( dblResult.toFixed(2) );
                    }
                }
                else {
                    $("#currency" + intID).val(0);
                }
                break;
			
            case 2:
                if (IsNumeric(dblSterling)) {
                    dblResult = Number(parseInt(dblSterling)) * (arrCurrencies[intID]["exchange"] * ((100 - arrCurrencies[intID]["sell"]) / 100));
                    $("#currency" + intID).val( dblResult.toFixed(2) );
                }
                else {
                    $("#sterling" + intID).val(0);
                }
                break;
			
        } // end switch
    }
}

//*** check mail form and the send ajax request

function validate(email) {

    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var address = email;

    if(reg.test(address) == false) {
        return false;
    }
    else {
        return true;
    }
}



function checkMailingList() {

    var strEmail = $('#mailingListEmail').val();
    if (validate(strEmail)) {
        $('#mailingListSubmitHolder').hide();
        $('#mailingResult').html('<img src="/images/ajax-loader-squares.gif">');
        doJqueryAjax('mailNothing', '', 'op=mailing&optionvalue=' + strEmail, 'GET', '');
    }
    else {
        $('#mailingResult').html('Please type in a valid email address');
    }
}

//************************************************************

function doJqueryAjax(strShow, strHide, strQueryData, strMethod, intReplace)  {
	
    var strBase		= '';
    if (window.location.protocol == 'https:') {
        strBase		= '';
    }
	
    var intDebug = 0;
    var strDataType = 'json';
    var strData = '';
    var strQuery = '';
	
    if (strMethod == 'POST') {
        strData = $("#" + strForm).serialize(); 
        strQuery = "?" + strQueryData;
    } 
    else {
        strData = strQueryData;
    }
	
    var strURL = strBase + '/~ace/ajax-ace.php' + strQuery;
	
    var strDebug =  "<strong>doJqueryAjaxM</strong>" + 
    " <br />strShow = " + strShow + 
    " <br />strHide = " + strHide + 
    "<br /> strQueryData = " + strQueryData + 
    "<br /> strMethod = " + strMethod + 
    "<br />";
	
	
    //$("#debug").html(strDebug);
	
    $.ajax({  
        type: 		strMethod,   
        url: 		strURL,  
        data: 		strData,
        cache: 		false,  
        dataType: 	'json',
		
        beforeSend: function() { 
		
            if (strHide.length > 0) {
                $("#" + strHide).hide(); //hide
            } 
            if (strShow.length > 0) {
                $("#waiting").show("slow"); //hide
                $("#" + strShow).hide(); //hide
                $("#" + strShow).html("");
            }
            if (intDebug > 0) {
                $("#ajaxurl").html("<p>" + strURL + " (" + strQueryData + ")</p>");
            }
        //alert(strURL);
        }, //show loading just when link is clicked
		
        success: function(objReturn, textStatus) {  
            //alert('returned ok');
            switch (strDataType) {
                case 'json': // JSON
					 
                    if (objReturn.result == 'success') {
                        strDebug += "objReturn.result = success" + " - " + objReturn.op + "<br />";
						
                        switch (objReturn.op) {
							
                            case 'mailing':
                                $('#mailingListEmail').val('')
                                $('#mailingListSubmitHolder').show();
                                $("#mailingResult").html(objReturn.html);
								
                                break;
							
                            case 'addcurrency':
								
                                $("#collectionNextRow").before(objReturn.html);
								
                                break;
							
                        }
						
                        if (objReturn.jquery) {
                            eval(objReturn.jquery);	
                        }
                    }
                    break;
            }
			
            $("#waiting").hide("slow"); //hide
            //$("#questionHolder").show("slow"); //animation
			
			
            if (intDebug > 0) {
                $("#ajax").html(html2entity(objReturn.html)); //animation
                $("#debug").html(strDebug);
                $("#debugSuccess").html(objReturn.debug);
            }
        },
		
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus + " " + errorThrown);
        }
		
    }); 
}
