/*
    Date Created:   Sep 2009
    Author:         Nick Coleman
    Content:        Functions which access the WCF sercies in the AppCode/services folder
    Pre-Requisites: jquery-1.4.1.js
    Notes:          This file should be minified before deployment using ajax minifier in deployment project,
                    http://javascriptcompressor.com/ or http://javascript.crockford.com/jsmin.html.
                    It is best to run through jslint prior to minifying
*/

// This function makes the JQuery Ajax call to the appropriate wcf service
var ServiceProxy =
{
    // Makes an ajax call  to the web service
    // baseURL : string : url of the web service to be called
    // datatype : string : The type of data that you're expecting back from the server (i.e. json, html, xml, jsonp, text)
    // contenttype : string : the content-type used to send data to server
    // method : string : the function in the web service to call
    // data : string : the data to send to the server
    // fnSuccess : string : A function to be called if the request succeeds. The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status
    // fnError : string : A function to be called if the request fails
    _doAjax: function(baseURL, datatype, contenttype, method, data, fnSuccess, fnError, async) {
        if (!data) { data = {}; }
        if (!fnError) { fnError = this._defaultErrorHandler; }
        if (async == undefined) { async = true; }
        
        $.ajax({
            type: "GET",
            url: baseURL + method,
            data: data,
            contentType: contenttype,
            dataType: datatype,
            success: fnSuccess,
            error: fnError,
            cache: false,
            async: async,
            dataFilter: function(data, dataType) {
                var response = jQuery.parseJSON(data);
                var jqVer = $().jquery.split('.');
                if (jqVer[1] >= 5 && dataType == 'json') {
                    // jQuery 1.5.0 and higher introduced pre-parsing of JSON into objects AFTER it leaves the data filter,
                    // so if this is a dataType == 'json' request, we need to prevent the double-parsing by returning
                    // the raw JSON here instead of the parsed object
                    if (response.hasOwnProperty("d")) {
                        // ensure data is never wrapped in the leading d property so rest of code works properly
                        // remove leading {"d:" and trailing }
                        data = data.slice(5, data.length - 1);
                    }
                    return data;
                }
                else {
                    // Pre jQuery 1.5 or dataType != 'json', we still need to parse the JSON manually
                    if (response.hasOwnProperty("d")) {
                        return response.d;
                    }
                    else {
                        return response;
                    }
                }
            }
        });
    },
    _defaultErrorHandler: function(xhr, status, error) {
        alert("error = " + xhr.statusText);
    }
};

// Creates the product service proxy to call the ProductService wcf service
ProductServiceProxy = function(url) { this._baseURL = url; };
ProductServiceProxy.prototype =
{
    // Returns all products currently available in the given kit selector
    // sid : integer : id of required kit selector
    GetSelectorProducts: function(sid, success, error) {
        var data = { SelectorId: sid };
        ServiceProxy._doAjax(this._baseURL, "json", "application/json; charset=utf-8", "GetSelectorProductsInfo", data, success, error);
    },
    // Returns the product information for given product
    // pid : integer : id of required product
    // getprinting : integer : determines whether to return printing information (1 = yes, 0 = no)
    GetProduct: function(pid, getprinting, success, error) {
        var data = { ProductId: pid, getPrinting: getprinting };
        ServiceProxy._doAjax(this._baseURL, "json", "application/json; charset=utf-8", "GetProductInfo", data, success, error);
    },
    // Returns all hero products linked to given product, the information returned is only pid and description
    // sid : integer : id of kit selector the parent product is in
    // pid : integer : id of parent product
    GetProductHeroes: function(sid, pid, success, error) {
        var data = { SelectorId: sid, ProductId: pid };
        ServiceProxy._doAjax(this._baseURL, "json", "application/json; charset=utf-8", "GetProductHeroesInfo", data, success, error);
    },
    // Sets the product plus promotion product that should be added to the basket when the main product is added to the basket
    // pid : integer : id of promotion product
    // vid : integer : id of promotion variation
    SetProductPlus: function(pid, vid, success, error) {
        var data = { ProductId: pid, VariationId: vid };
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "SetProductPlus", data, success, error);
    },
    // Removes the product plus promotion product that should be added to the basket when the main product is added to the basket
    RemoveProductPlus: function(success, error) {
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "RemoveProductPlus","", success, error);
    },
    // Sets the product plus promotion product that should be added to the basket when the main product is added to the basket
    // pid : integer : id of main added product
    // vid : integer : id of main added variation
    // heropid : integer : id of added hero product
    // name : string : any name printing that is required on the main product
    // number : string : any number printing that is required on the main product
    // badges : integer : id of badges required on the main product or hero product
    AddToBasket: function(pid, vid, heropid, name, number, badges, success, error) {
    var data = { ProductId: pid, VariationId: vid, HeroProductId: heropid, PrintingName: name, PrintingNumber: number, BadgeId: badges };
        ServiceProxy._doAjax(this._baseURL, "json", "application/json; charset=utf-8", "AddToBasket", data, success, error);
    },
    SearchProducts: function(text, success, error) {
        var data = { searchText: text };
        ServiceProxy._doAjax(this._baseURL, "json", "application/json; charset=utf-8", "ProductSearch", data, success, error);
    }
};

// Creates the customer service proxy to call the CustomerService wcf service
CustomerServiceProxy = function(url) { this._baseURL = url; };
CustomerServiceProxy.prototype =
{
    // Adds a customer to the mail list
    // email : string : the email address of customer to add to basket
    AddCustomerToMailList: function(email, success, error) {
        var data = { Email: email };
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "addCustomerToMailList", data, success, error);
    },
    // Adds a customer to the mail list with extended properties
    // email : string : the email address of customer to add to mail list
    // dob : string : the date of birth of customer to add to mail list
    // country : integer : the country id of customer to add to mail list
    AddCustomerToMailListExtended: function(email, dob, country, success, error) {
    var data = { Email: email, DOB: dob, CountryId: country };
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "addCustomerToMailListExtended", data, success, error);
    }
};

// Creates the general service proxy to call the GeneralService wcf service
GeneralServiceProxy = function(url) { this._baseURL = url; };
GeneralServiceProxy.prototype =
{
    // Returns the content of the leaf in the given branch
    // branch : integer : id of the content branch
    // leaf : string : the name of the leaf to return
    // async : boolean : states whether the call should be made async or not. if omitted it will be set to true
    GetLeafContent: function(branch, leaf, success, error, async) {
        var data = { BranchId: branch, Leaf: leaf };
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "GetLeafContent", data, success, error, async);
    }
};

// Creates the basket service proxy to call the BasketService wcf service
BasketServiceProxy = function(url) { this._baseURL = url; };
BasketServiceProxy.prototype =
{
    // Inserts a printing item for the given basket item
    // basketid : integer : id of the current basket
    // basketitemid : integer : id of the current basket item
    // printypeid : integer : id of the type of printing item being added (ee_printing_type)
    // qty : integere : qty of items being added
    // desc : string : the printing to be added
    // pricewholesale : decimal : wholesale price
    // priceretail : decimal : retail price
    InsertPrintingItem: function(basketitemid, printypeid, qty, desc, pricewholesale, priceretail, success, error) {
        var data = { BasketItemId: basketitemid, PrintTypeID: printypeid, Quantity: qty, printDescription: desc, priceWholeSale: pricewholesale, priceRetail: priceretail };
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "InsertPrintingItem", data, success, error);
    },

    // Removes a printing item for the given basket item
    // basketitemid : integer : id of the current basket item
    // printypeid : integer : id of the type of printing item being removed (ee_printing_type)
    RemovePrintingItem: function(basketitemid, printypeid, success, error) {
        var data = { BasketItemId: basketitemid, PrintTypeID: printypeid };
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "RemovePrintingItem", data, success, error);
    },
    
    // Updates a printing item for the given basket item
    // basketitemid : integer : id of the current basket item
    // printypeid : integer : id of the type of printing item being updated (ee_printing_type)
    // printdesc : string : the printing to be updated 
    UpdatePrintingItem: function(basketitemid, printypeid, printdesc, success, error) {
        var data = { BasketItemId: basketitemid, PrintTypeID: printypeid, PrintDescription: printdesc };
        ServiceProxy._doAjax(this._baseURL, "html", "application/html; charset=utf-8", "UpdatePrintingItem", data, success, error);
    },
    
    // Updates a printing item for the given basket item
    // basketitemid : integer : id of the current basket item
    // printypeid : integer : id of the type of printing item being updated (ee_printing_type)
    // printdesc : string : the printing to be updated
    RemovePrintingItemsByType: function(printypeid, success, error) {
        var data = { PrintTypeID: printypeid };
        ServiceProxy._doAjax(this._baseURL, "json", "application/json; charset=utf-8", "RemovePrintingItemsByType", data, success, error);
    }
};


