var waitingForUpload = false;
var HWNDWaiting = "";

$(function()
{
    $("#price").blur(function()
    {
        var price = $(this).val();
        price = price.replace(".", "");
        price = price.replace(",", "");
        $(this).val(price);
    });
    $(".req").addClass("required");
    $(".req").blur(function(){$(this).val() == "" ? $(this).addClass("required") : $(this).removeClass("required");});

    $("#txtEmail").blur(function(){waitingForUpload = false;refreshAds();});

    $("#butSaveAccount").click(function()
    {
        if (validateDetailsForm())
        {
            $("#accountDetails").hide();
            $("#advertDetails").show();
            $("#advertList").show();
        }
    });
    
    $("#butAddImg").click(function()
    {
        var filename = $("#image").val();
        if (filename == "")
        {
            $.prompt("Please select a file to add");
            return false;
        }

        $.cloneToDB({
            dbName: "images_db",
            elementID: "image"
        });
        $.cloneToDB({
            dbName: "images_db",
            elementID: "txtImageDescription"
        });
        $("#divImages").displayDB({dbName: "images_db"});
    });

    $("#butSaveAd").click(function()
    {
        var referalCode = $("#txtReferalCode").val();

        // Make sure fields with a req class have been filled in
            $.queue({
                codeBase: validateForm,
                isFunction: true
            })

        // Check the promotional code (Doesn't run stright away. It's added to the execution queue
            var promoCode = $("#txtPromoCode").val();
            /*if ( promoCode != "")
            {
                $.executeCommand({
                    command: "checkPromoCode",
                    addToQueue: true,
                    extraItems:
                    [ 
                        {name: "code", value: promoCode}
                    ]
                });
            }*/

        // Save account
            $.executeCommand({
                command: "saveAccount",
                addToQueue: true,
                form: "frmAccount",
                passAlong: 
                [
                    "aid"
                ]
            });

        // Save the advert
        var adID = $("#adID").val();
            $.executeCommand({
                command: "saveAdvert",
                addToQueue: true,
                form: "frmCreateAdvert",
                extraItems:
                [
                    {name: "status", value: "0"},
                    {name: "code", value: promoCode},
                    {name: "adID", value: adID},
                    {name: "referalCode", value: referalCode}
                ],
                passAlong:
                [
                    "adID"
                ]
            });

        // Upload any images
            $.queue({
                codeBase: startImagesUpload,
                isFunction: true,
                ignoreReturn: true
            });

        // Get the advert list
            $.queue({
                codeBase: refreshAds,
                isFunction: true
            });
            
        // Execute the queue
            $.executeQueue();

    });

    $("#butCancelEdit1, #butCancelEdit2").click(function()
    {
        $("#adID").val(0);
        $("#divCurrentImages").empty();
        $("#frmCreateAdvert").clearForm();
        $("#butCancelEdit1, #butCancelEdit2").hide();
        $(".req").each(function()
        {
            if ($(this).val() == "") $(this).addClass("required");
        })
    })

    $("#butPay").click(function()
    {
        var promoCode = $("#txtPromoCode").val();
        var accountID = $("#aid").val();
        $("#code").val(promoCode);
        $("#account").val(accountID);
        $("#frmPay").submit();
    });
});

function clearImages()
{
    $("#divCurrentImages").empty();
}

function refreshAds()
{
    // All this crap is so we wait until the images are finished uploading
        if (HWNDWaiting)
            clearInterval(HWNDWaiting);
    
        if (waitingForUpload)
        {
            HWNDWaiting = setInterval(refreshAds, 200);
            return false;
        }
        waitingForUpload = true;
    // End of crap

    var mode = $("#m").val();
    var aid = $("#aid").val();
    var promoCode = $("#txtPromoCode").val();
    var email = $("#txtEmail").val();
    $.executeCommand({
        command: "refreshAds",
        extraItems:
        [
            {name: "m", value: mode},
            {name: "aid", value: aid},
            {name: "email", value: email},
            {name: "code", value: promoCode}
        ]
    });
}
function refreshAds_callback ( data )
{
    var html = "";
    var mode = $("#m").val();

    $(data.adList).each(function(i)
    {
        html += data.adList[i] + "<br><hr><br>";
    });

    var paymentDetails = "";
    var totalPrice = data.totalPrice;
    var adPrice = data.adPrice;
    var adMonthlyPrice = data.adMonthlyPrice;
    var totalMonthlyPrice = data.totalMonthlyPrice;
    var remainingAds = data.remainingAds;
    var jobLot = data.jobLot;
    var aid = data.aid;

    $("#aid").val(aid);

    paymentDetails = "<p>Your adverts will cost <strong>&pound;" + totalPrice + "</strong> " + (adPrice > 0 ? "(<strong>&pound;" + adPrice + "</strong> per advert)" : "") + "</p>";

    if (totalPrice > 0 && ! jobLot)
    {
        $("#butPay").val("Make Payment");
        paymentDetails += "<p>Or <strong>&pound;" + totalMonthlyPrice + "</strong> " + (adMonthlyPrice > 0 ? "(<strong>&pound;" + adMonthlyPrice + "</strong> per advert)" : "") + " per month";
    } else {
        $("#butPay").val("Make adverts live");
    }

    if(remainingAds > 0)
    {
        paymentDetails += "<p>You can add another <strong>" + remainingAds + "</strong> with this promotional code</p>";
    } else if (remainingAds < 0) {
        paymentDetails += "<p>You can place no more adverts with this promotional code.</p>";
    }

    $("#paymentDetails").html(paymentDetails);

    $("#currentAds").html(html);
    $(".delete").click(function()
    {
        var advertID = $(this).attr("rel");
        $.prompt("Are you sure you wish to delete this advert?", 
        {
            buttons:{Yes:true,No:false}, 
            callback: function(clicked, msg){
                        if (clicked){
                            $.executeCommand({
                                command: "deleteAdvert",
                                extraItems:
                                [
                                    {name: "adID", value: advertID},
                                    {name: "m", value: mode}
                                ]
                            });
                        }
                      }
        })
    });
    //$("#divCurrentImages").empty();
    $(".edit").click(function()
    {
        $("#butCancelEdit1,#butCancelEdit2").show();
        var advertID = $(this).attr("rel");
        $.executeCommand({
            command: "getAdvert",
            extraItems:
            [
                {name: "adID", value: advertID},
                {name: "m", value: mode}
            ]
        });
    });
}

function cancelEdit()
{
    $("#adID").val(0);
    $("#frmCreateAdvert").clearForm();
    $("#butCancelEdit1, #butCancelEdit2").hide();
    $("#divCurrentImages").empty();
}

function getAdvert_callback( data )
{
    for ( var j in data )
    {
        $("#" + j).val(data[j]);
    }

    $("#adID").val(data.adID);
    $("#divCurrentImages").empty();
    for ( var j in data.images)
    {
        var image = data.images[j];
        var img = "<img src='" + image + "' border='0'> <a class='deleteImage' href='javascript:void(0)' rel='" + j + "'>delete</a><br><br>";
        $("#divCurrentImages").append(img);
    }

    $(".deleteImage").click(function()
    {
        var advertID = $("#adID").val();
        var imageID = $(this).attr("rel");
        $.executeCommand({
            command: "deleteImage",
            extraItems:
            [
                {name: "adID", value: advertID},
                {name: "imgID", value: imageID}
            ]
        });
    });
    
    $(".req").each(function()
    {
        if ($(this).val() != "") $(this).removeClass("required");
    })
}

function deleteImage_callback()
{
    waitingForUpload = false;
    $("#divCurrentImages").empty();
    refreshAds();
    var advertID = $("#adID").val();
    var mode = $("#m").val();
    $.executeCommand({
        command: "getAdvert",
        extraItems:
        [
            {name: "adID", value: advertID},
            {name: "m", value: mode}
        ]
    });
}

function deleteAdvert_callback()
{
    waitingForUpload = false;
    $("#frmCreateAdvert").clearForm();
    refreshAds();
}

function validateForm()
{
    var ret = true;
    $(".req").each(function()
    {
        if ($(this).val() == "")
        {
            ret = false;
            return;
        }
    });
    
    if ( !ret )
    {
        $.prompt("Please fill in the fields marked red");
    }
    return ret;
}

function validateDetailsForm()
{
    var name = $("#txtName").val();
    var email = $("#txtEmail").val();
    var telephone = $("#txtTelephone").val();
    
    if (name == "" || email == "" || telephone == "")
    {
        $.prompt("All the contact details fields are required");
        return false;
    }
    return true;
}

function checkPromoCode_callback( data )
{
    if ( data.valid == "0")
    {
        $.prompt( "Invalid promotional code." );
        return false;
    }
    
    if (data.valid == "-1")
    {
        $.prompt("You have reached the limit for this promotional code");
        return false;
    }
    return true;
}

function saveAccount_callback( data )
{
    if ( data.aid == "0" || data.aid == "")
    {
        $.prompt( "There was a problem creating your account" );
        return false;
    }

    $("#aid").val(data.aid);
    return true;
}

function saveAdvert_callback ( data )
{
    if ( data.id == "" || data.id == "0")
    {
        $.prompt("There was a problem saving the advert");
        return false;
    }
    
    cancelEdit();
    
    $(".req").each(function()
    {
        if ($(this).val() == "") $(this).addClass("required");
    })
    return true;
}

function startImagesUpload(adID)
{
    if (adID === undefined)
    {
        alert("No advertID, Unable to upload images");
        waitingForUpload = false;
        return false;
    }
    var totalImages = $(".image").size();
    if (!totalImages) 
    {
        waitingForUpload = false;
        return true;
    }
    $.blockUI({
        width: '400',
        fontWeight: 'bold'
    });
    var currentImage = 0;
    return uploadTempFiles("image", "txtImageDescription", currentImage, totalImages, adID);
}

function uploadTempFiles(fileElement, descriptionElement, currentImage, totalImages, adID)
{
    $("#divImages").displayDB({dbName: "images_db"});
    if (currentImage == totalImages)
    {
        // We're done
        $.unblockUI();
        waitingForUpload = false;
        return true;
    } else {
        // Check to see if the element we are going to do actually exists (It could have been deleted)
        // because this function assumes that all the image_0, image_1 elements are consecutive.  If
        // for example there are 3 elements and the middle one gets deleted this function will fail
        // so if we check for the existence of the element and it doesn't exist we increase the
        // total images so it keeps looking at higher numbers.
        if (!$("#" + fileElement + "_" + currentImage).size())
        {
            return uploadTempFiles(fileElement, descriptionElement, currentImage + 1, totalImages + 1, adID);
        }

        // Update the blockUI message
            var file = $("#" + fileElement + "_" + currentImage).val();
            file = unescape(file).match(/[^\/&&^\\]*\.(jpg|gif|png)/gi);
            var message = "Uploading " + file + "<br><img src='/images/large_indicator.gif'>";

        $("#blockedContent").html(message);

        $.ajaxFileUpload
        ({
            url:"/servcom/fileupload.php", 
            secureuri:false,
            fileElementId: fileElement + "_" + currentImage,
            dataType: "json",
            descriptionElement: descriptionElement + "_" + currentImage,
            adID: adID,
            async: false,
            success: function (data, status)
            {
                if(typeof(data.error) != 'undefined')
                {
                    if(data.error != '')
                    {
                        alert(data.error);
                    }
                } else {                        
                    $("#" + fileElement + "_" + currentImage).remove();
                    $("#" + descriptionElement + "_" + currentImage).remove();
                    currentImage++;
                    return uploadTempFiles(fileElement, descriptionElement, currentImage, totalImages, adID);
                }
            },
            error: function (data, status, e)
            {
                if (data.responseText != "")
                {
                    //alert(data.responseText);
                    $.unblockUI();
                }
                $("#" + fileElement + "_" + currentImage).remove();
                $("#" + descriptionElement + "_" + currentImage).remove();
                currentImage++;
                return uploadTempFiles(fileElement, descriptionElement, currentImage, totalImages, adID);
            }
        });
    }
}
