﻿/*Global Variable declarations */

/* Javascript PROTOTYPES : TODO: take it out of this file */

/* ARRAYS */
//Turns an array to stuff like 1,2,3,4
Array.prototype.Flatten = function(provider) {
    if ((this !== null) && (this !== undefined) && (this.constructor.toString().indexOf("Array") !== -1)) {
        var data = '';
        for (i = 0; i < this.length; i++) {
            if (provider === undefined) {
                data += ((i + 1) != this.length) ? (this[i] + ",") : (this[i]);
            }
            else {
                switch (provider) {
                    case documentConfig.arrayTrafTours:
                        data += ((i + 1) != this.length) ? ("tours=" + this[i] + "&") : ("tours=" + this[i]);
                        break;
                }
            }
        }
        return data;
    }
    return "";
};

/* Strings */

String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

String.prototype.isValidEmailFormat = function() {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (reg.test(this) === false) {
        return false;
    }
    return true;
};

var ajaxStatuses = { InProgress : 1000, Available : 1001 };

var ajaxStatus = ajaxStatuses.Available;


var serviceBase = { link: function() {
    if (location.hostname.indexOf("localhost")) {
        return "/TT/Services/TrafalgarSiteClientSideCalls.asmx/";
    }
    else {
        return "/Services/TrafalgarSiteClientSideCalls.asmx/";
    }
}};

var documentConfig = {maxBrochureDownloadRequest: 3, arrayTrafTours: "TrafTours", titleStateBag : ""};

//For now, we'll just deal with one
var brochDownloadStatusCodes = { ERRORGENERATING : "1000", ERRORSAVING : "1001", ERROREMAILING: "1002", EMAILSUCCESS: "1010" };
var validationTypes = { EMPTYVALUE : 1000, EMAILFORMAT : 1001 };

var defaultDataType = "json";
var defaultResponseType = "application/json; charset=utf-8";

/*
Global objects
*/

var defaultCallBack = {
    onSuccess: function(data, textStatus, XMLHttpRequest) {
        //alert(data.d);
    },
    onError: function() {
        //alert("error");
    },
    onComplete: function() {
        //alert("completre");
    }
};

//Used when a form needs to be rendered
var brochureMailOrderCallBack = {
    onSuccess: function(data, textStatus, XMLHttpRequest) {
        $("#confirmWinText").html(data.d);
    },
    onError: function() {
        //alert("error");
    },
    onComplete: function() {
        //alert("completre");
    }
};

//Used when an order is submitted
var brochureMailOrderSendCallBack = {
    onSuccess: function(data, textStatus, XMLHttpRequest) {
        popUpWindowAction.setBodyTemplateContent(data.d);
    },
    onError: function() {
        //alert("error");
    },
    onComplete: function() {
        //alert("completre");
    }
};

var brochureMailOrderFormCallBack = {
    onSuccess: function(data, textStatus, XMLHttpRequest) {
        popUpWindowAction.setWindowInstance();
        popUpWindowAction.setTitle("Mail Order");
        popUpWindowAction.setBodyTemplateContent(data.d);
        popUpWindowAction.showWindow(); 
    },
    onError: function() {
        //alert("error");
    },
    onComplete: function() {
        //alert("completre");
    }
};

//Used when a brochure is to be downloaded, sends all the sections 
//within the Brochure back as as string
var brochurePDFDownloadCallBack = {
    onSuccess: function(data, textStatus, XMLHttpRequest) {
        popUpWindowAction.setBodyTemplateContent(data.d);
        //Set title
        popUpWindowAction.setTitle($("#brochureSectionDynamicTitle").html());
    },
    onError: function() {
        //alert("error");
    },
    onComplete: function() {
        //alert("completre");
    }
};

//Used when a brochure is to be downloaded, sends the sections MVCodes to the server,
//The server creates the PDF and stores it witnin a folder
//This sends back the pdf name which will then be sent
var brochurePDFCreateCallBack = {
    onSuccess: function(data, textStatus, XMLHttpRequest) {
        //popUpWindowAction.setBodyTemplateContent(data.d);
        //alert(data.d);
        switch (data.d) {
            case brochDownloadStatusCodes.ERRORGENERATING:
            case brochDownloadStatusCodes.ERRORSAVING:
                brochureDownloadOperations.showMessageOnForm("<span style=\"color:red;\">We are sorry but an error occurred while trying to generate your brochure.</span>");
                break;
            case brochDownloadStatusCodes.ERROREMAILING:
                brochureDownloadOperations.showMessageOnForm("<span style=\"color:red;\">We are sorry but an error occurred while trying to send your brochure.</span>");
                break;
            case brochDownloadStatusCodes.EMAILSUCCESS:
                brochureDownloadOperations.showMessageOnForm("<span style=\"color:green;text-align:left;\">Your brochure has been sent successfully.</span>");
                break;
            default:
                var url = "DownLoadBrochure.aspx?ref=" + escape(data.d);
                var msg = "If you can’t see the downloaded brochure, please click the <a target=\"_blank\" style=\"text-decoration:underline;\" href=\"" + url + "\">following link</a> to be taken to it.";
                brochureDownloadOperations.showMessageOnForm("<span style=\"color:green;line-height:normal;text-align:left;\">Your brochure has been generated successfully. <br />" + msg + "</span>");
                $("#myBrochureFrame").attr("src", url);
                break;
        }
    },
    onError: function() {
        brochureDownloadOperations.showMessageOnForm("<span style=\"color:red;\">We are sorry but an error occurred while trying to generate your brochure.</span>");
    },
    onComplete: function() {
        ajaxStatus = ajaxStatuses.Available;
        $(".downloadSpinner").hide();
        $(".downloadMessage").show();
    },
    beforeSend: function() {
        ajaxStatus = ajaxStatuses.InProgress;
        brochureDownloadOperations.hideMessageOnForm();
        $(".downloadSpinner").show();
    },
    onInterupt: function() {
        brochureDownloadOperations.showMessageOnForm("<span style=\"color:red;\">Please wait for your previous request to complete</span>");
    }
};

var winInstance = null;

//TODO, how to make instance this???? there is sum loooong tin in here!
var popUpWindowAction = {
    setWindowInstance: function() {
        //if (winInstance == null) {
        var win = $('#popUpBoxContainer');
        if (win !== null && win != undefined) {
            winInstance = win;
        }
        //}
    },
    setTitle: function(title) {
        if (winInstance !== null && winInstance !== undefined) {
            winInstance.find("#confirmWinHeader").html(title);
        }
    },
    setBodyTemplate: function(id) {
        if (winInstance !== null && winInstance !== undefined) {
            winInstance.find("#containerBody").html($(id).html());
        }
    },
    setPopUpStyle: function(styles) {
        if (winInstance !== null && winInstance !== undefined) {
            $(".jqmWindow").attr("style", styles)
        }
    },
    setBodyTemplateContent: function(content) {
        if (winInstance !== null && winInstance !== undefined) {
            winInstance.find("#containerBody").html(content);
        }
    },
    showWindow: function() {
        if (winInstance !== null && winInstance !== undefined) {
            winInstance.jqmShow();
        }
    },
    hideWindow: function() {
        if (winInstance !== null && winInstance !== undefined) {
            winInstance.jqmHide();
        }
    }
};

function removeUserOrder(node, id) {
    //do ajax call to remove from session
    createRemoteRequest("DeleteUserBrochure", { brochureID: id }, null, null);
    //remove node
    $(node).parent().remove();
}

var validationActions =
{
    validateTextControl: function(control) {
        return ($(control).val()) === "" ? false : true;
    }
}

var isValid;

var brochureDownloadOperations = {
    showMessageOnForm: function(msg) {
        $(".downloadMessage").html(msg);
        $(".downloadMessage").show();
    },
    hideMessageOnForm: function(msg) {
        $(".downloadMessage").html("");
        $(".downloadMessage").hide();
    },
    getCheckedCount: function() {
        return $("[name=checkMeDownload]:checked").length;
    },
    validate: function(args) {
        if (this.getCheckedCount() > documentConfig.maxBrochureDownloadRequest) {
            //Now allowed
            $(args).attr('checked', false);
            this.showMessageOnForm("<span style=\"color:red;\">You may not select more than " + documentConfig.maxBrochureDownloadRequest + " brochure sections</span>");
        }
    },
    generateMVCodes: function() {
        var masterMVCodes = new Array();
        //Now we need to get the MVCodes
        $("[name=checkMeDownload]:checked").each(function(i) {
            var thisMvCodes = $(this).attr("data");
            if (thisMvCodes !== null) {
                var mvCodes = thisMvCodes.split(",");
                for (i = 0; i < mvCodes.length; i++) {
                    if ($.inArray(mvCodes[i], masterMVCodes) === -1) {
                        //the MVCode is not contained within the master array
                        //We have to ensure that MVCodes for requests are unique otherwise
                        //The brochure engine will refuse it
                        masterMVCodes.push(mvCodes[i]);
                    }
                }
            }
        });
        return masterMVCodes;
    },
    download: function() {
        if (this.getCheckedCount() === 0) {
            this.showMessageOnForm("<span style=\"color:red;\">You must select at least 1 brochure section to download</span>");
            return;
        }
        createRemoteRequest("CreatePDFForSections",
            {
                mvCodes: this.generateMVCodes().Flatten(),
                brochureName: documentConfig.titleStateBag,
                action: 1,
                firstName: "",
                lastName: "",
                email: ""
            }
        , brochurePDFCreateCallBack, null);
    },
    validateField: function(ctrlRef, type) {
        if ((type === undefined) || (type == validationTypes.EMPTYVALUE)) {
            //We are doing just a empty string/value match
            if ($("#" + ctrlRef).val().trim() === "") {
                $("#" + ctrlRef).parent().find(".brochFieldError").html(" *");
                return false;
            }
            else {
                $("#" + ctrlRef).parent().find(".brochFieldError").html("");
                return true;
            }
        }
        else {
            switch (type) {
                case validationTypes.EMAILFORMAT:
                    if ($("#" + ctrlRef).val().trim().isValidEmailFormat() === false) {
                        $("#" + ctrlRef).parent().find(".brochFieldError").html(" *");
                        return false;
                    }
                    return true;
                    break;
                default:
                    return false;
            }
        }
    },
    sendEmail: function() {
        //We need to validate the form
        if (this.getCheckedCount() === 0) {
            this.showMessageOnForm("<span style=\"color:red;\">You must select at least 1 brochure section to download</span>");
            return;
        }
        //Validate fields
        var isValidFname = true, isValidLName = true, isValidEmail = true;

        isValidFname = this.validateField("sendBrochureFirstName");
        isValidFname = this.validateField("sendBrochureLastName");
        isValidEmail = this.validateField("sendBrochureEmail");

        if (isValidEmail) {
            //Test for valid email format
            isValidEmail = this.validateField("sendBrochureEmail", validationTypes.EMAILFORMAT);
        }

        if (!isValidFname || !isValidFname || !isValidEmail) {
            this.showMessageOnForm("<span style=\"color:red;\">Please fill out the required fields below</span>");
            return;
        }
        else {
            createRemoteRequest("CreatePDFForSections",
             {
                 mvCodes: this.generateMVCodes().Flatten(),
                 brochureName: documentConfig.titleStateBag,
                 action: 0,
                 firstName: $("#sendBrochureFirstName").val().trim(),
                 lastName: $("#sendBrochureLastName").val().trim(),
                 email: $("#sendBrochureEmail").val().trim()
             },
            brochurePDFCreateCallBack, null);
        }
    }
};

var validateBrochureOrderForm = {

    validateForm: function(region) {
        //We need to get all fields
        var type;
        var validFlag = true;
        var controlParent;
        isValid = true;
        $(".formFieldRight").each(function(i) {
            //Is it required
            if ($(this).attr("required") === "True") {
                //We need to validate on this field
                type = $(this).attr("type");
                switch (type) {
                    case "Text":
                        validFlag = validationActions.validateTextControl($(this).find("input"));
                        controlParent = $(this).parent().find("td.validationField");

                        if (controlParent === null || controlParent === undefined) {
                            controlParent = $(this).parent().find("td.validationFieldInvalid");
                        }

                        if (!validFlag) {
                            isValid = false;
                            controlParent.html("*");
                        }
                        else {
                            controlParent.html("");
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        if (isValid) {
            this.submitForm(region);
        }
    }, //End Validate form
    submitForm: function(region) {
        var vals = null;
        switch (region) {
            case "USA":
                //Get all inputs
                var vals = {
                    lstTitle: $("[name = lstTitle]").val(),
                    txtFirstName: $("[name = txtFirstName]").val(),
                    txtLastName: $("[name = txtLastName]").val(),
                    txtAddress: $("[name = txtAddress]").val(),
                    txtAddress2: $("[name = txtAddress2]").val(),
                    txtCity: $("[name = txtCity]").val(),
                    lstStates: $("[name = lstStates]").val(),
                    txtZip: $("[name = txtZip]").val(),
                    txtCountry: $("[name = txtCountry]").val(),
                    txtPhone: $("[name = txtPhone]").val(),
                    chkTravelProf: $("[name = chkTravelProf]").val(),
                    txtEmail: $("[name = txtEmail]").val(),
                    chkOptIn: $("[name = chkOptIn]").val()
                };
                //console.log(vals);
                break;
        }

        createRemoteRequest("SendUserOrderUSA", vals, brochureMailOrderSendCallBack, null);
    }
};

function addToBrochureMailOrder(id, title) {
    popUpWindowAction.setWindowInstance();

    if (winInstance !== null && winInstance != undefined) {
        
        //Send server request
        createRemoteRequest("UpdateUserBrochureMailOrder", { brochureID: id, brochureName: title }, brochureMailOrderCallBack, null);

        popUpWindowAction.setTitle("Item added to your order");
        popUpWindowAction.setBodyTemplate("#confirmTemplateBox");
        popUpWindowAction.showWindow(); 
    }
}

function getSectionsForBrochure(id, title) {
    
    popUpWindowAction.setWindowInstance();

    if (winInstance !== null && winInstance != undefined) {
        documentConfig.titleStateBag = title;
        //Send server request
        createRemoteRequest("GetBrochureSections", { brochureID: id }, brochurePDFDownloadCallBack, null);
        popUpWindowAction.setTitle("Select Brochure Section");
        popUpWindowAction.setBodyTemplate("#downloadBrochureTemplateBox");
      
       
        popUpWindowAction.setPopUpStyle("top: 10%;"); //Modify top position
        popUpWindowAction.showWindow();
    }
}

function getOrderForm() {
    createRemoteRequest("GetUserBrochureMailOrder", {}, brochureMailOrderFormCallBack, null);
}

function createRemoteRequest(method, args, callBack, responseFormat) {
    
    var contentResponseType = ((responseFormat === null) || (responseFormat === undefined)) ? defaultResponseType : responseFormat;

    callBack = ((callBack === null) || (callBack === undefined)) ? defaultCallBack : callBack;

    if (ajaxStatus !== ajaxStatuses.Available) {
        //We have set a blocking call in a call back, we will not do this request as it's still running
        if (callBack.onInterupt !== undefined) {
            callBack.onInterupt(); //call the function assigned to the call back when a call is interupted
        }
        return;
    }

    $.ajax({
        type: "POST",
        contentType: contentResponseType,
        url: serviceBase.link() + method,
        data: $.toJSON(args), //'{"brochureID" : 1 }',
        dataType: defaultDataType,
        success: callBack.onSuccess,
        error: callBack.onError,
        complete: callBack.onComplete,
        beforeSend: function() {
            if (callBack.beforeSend !== undefined) {
                return callBack.beforeSend();
            }
        }
    });
}

$(document).ready(
    function() {
        //Order confirm Modal template
        $('#popUpBoxContainer').jqm({ overlay: 88, modal: true, trigger: false });

        //$('#orderForm').jqm({ overlay: 88, modal: true, trigger: false });


        // Trigger for add to mail order set-up
        //$('img.requestButtonOptionImgMail').click(function() {
            //addToBrochureMailOrder($(this).parent().attr("id"), $(this).parent().attr("title"));
            //return false;
        //});

        // Trigger for download e-brochure
        $('img.requestButtonOptionImgDownload').click(function() {
            getSectionsForBrochure($(this).parent().attr("id"), $(this).parent().attr("title"));
            return false;
        });


        //Hides form
        $('div.lightBlueBoxConfirmHeaderIcontContainer').click(function() {
            popUpWindowAction.hideWindow();
            return false;
        });
        //

        // Trigger for showing order form
        $('#getOrderForm').click(function() {
            getOrderForm(this.id, this.title);
            return false;
        });
});
