/* Global Var */
var Invoker;
if (!Invoker) Invoker = {};
var testurl = true; // false for local testing
if(!testurl){
    $.cookie('username','worldexport');
}
var _username = $.cookie('username');
var _user_id=null;var _seller_name="";var _asa_time="";var _default_inventory_fields=null;
var _asa_text = "Thank you for choosing UK-Liquidation. It appears we do not have an agreement on file for you, to sell on UK-Liquidation.  Please contact us at (01249) 464750, and an Account Management representative will help you submit your auction(s).";
var _default_reports_range = -90; //(- 90 days)
/*  End Global Var  */
/* Urls used in code */

Invoker.GetActiveAuctions = function(params, callback) {
    //var qs = Invoker.hashToQuery(params);
    var url = (testurl) ? _LSIURL + "/api/v1/auction//search?user_id=" + _user_id + "&record_status=A&open_time<="+Invoker.GetDateTime()+"&close_time>="+Invoker.GetDateTime()+"&_sort=%2Bclose_time&_select=auction_id&_select=title&_select=current_bid&_limit=3" :
    "../data/activeauctions.json";
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Retrieve Active Auctions Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetReportsData = function(request, params, callback){
    var url;var f ;var t;
    switch (request.type) {
        case "active":
            url = testurl ? _LSIURL + "/api/v1/auction//search?user_id=" +
            _user_id + "&record_status=A&_select=record_status" +
            "&_select=title&_select=auction_id&_select=current_bid&_select=address_name&_select=category&_select=reference_notes&_select=close_time&_select=open_time&_count=1&_select=size_classification&_select=previous_auction_id"+
            "&_sort=%2Bclose_time"+
            "&_page=" + (params.page || 1) +
            "&_per_page=" + (params.per_page || CONFIG.DEFAULT_PAGESIZE) :  "../data/activeauctions.json?";
            if(params.sortby=="date")url += "&open_time>=" + params.fromDate + "&open_time<=" + params.toDate;
            else url += "&open_time>=" + Invoker.GetDateTime("-1") + "&open_time<=" + Invoker.GetDateTime();
            break;
        case "psell":
            url = testurl ? _LSIURL + "/api/v1/transaction//search?seller_id=" +
            _user_id + "&transaction_state_code=PSELL&transaction_state_code=COMPL&_select=title" +
            "&_select=auction_id&_select=transaction_state_code&_select=transaction_id&_select=auction.size_classification&_select=tracking_id" +
            "&_select=auction.address_name&_select=auction.close_time&_select=amount&_select=auction.reference_notes&_select=auction.address_id&_select=state_change_time" +
            "&_count=1&_sort=%2Bstate_change_time"+
            "&_page=" + (params.page || 1) +
            "&_per_page=" + (params.per_page || CONFIG.DEFAULT_PAGESIZE) : "../data/completes&psell.json?";
            if(params.sortby=="date")url += "&state_change_time>=" + params.fromDate + "&state_change_time<=" + params.toDate;
            else url += "&state_change_time>=" + Invoker.GetDateTime("-1") + "&state_change_time<=" + Invoker.GetDateTime();
            break;
        case "dispute":
            url = testurl ? _LSIURL + "/api/v1/transaction//search?seller_id=" +
            _user_id + "&transaction_state_code=DISIT&_select=title&_select=dispute.reason_code" +
            "&_select=auction_id&_select=transaction_state_code&_select=transaction_id&_select=auction.size_classification&_select=tracking_id" +
            "&_select=auction.address_name&_select=auction.close_time&_select=amount&_select=auction.reference_notes&_select=auction.address_id&_select=state_change_time" +
            "&_count=1&_sort=%2Bstate_change_time"+
            "&_page=" + (params.page || 1) +
            "&_per_page=" + (params.per_page || CONFIG.DEFAULT_PAGESIZE) : "../data/dispute.json?";
            if(params.sortby=="date")url += "&state_change_time>=" + params.fromDate + "&state_change_time<=" + params.toDate;
            else url += "&state_change_time>=" + Invoker.GetDateTime("-1") + "&state_change_time<=" + Invoker.GetDateTime();
            break;
        case "review":
            url = testurl ? _LSIURL + "/api/v1/auction//search?user_id=" +
            _user_id + "&record_status=P&_select=record_status" + //&record_status=R"
            "&_select=title&_select=auction_id&_select=current_bid&_select=creation_time&_select=address_name&_select=category&_select=reference_notes&_select=close_time&_select=open_time&_count=1&_select=size_classification&_select=previous_auction_id"+
            "&_sort=%2Bcreation_time"+
            "&_page=" + (params.page || 1) +
            "&_per_page=" + (params.per_page || CONFIG.DEFAULT_PAGESIZE) : "../data/activeauctions.json?";
            if(params.sortby=="date")url += "&creation_time>=" + params.fromDate + "&creation_time<=" + params.toDate;
            else url += "&creation_time>=" + Invoker.GetDateTime("-1") + "&creation_time<=" + Invoker.GetDateTime();
            break;
        case "cancel":
            if(params.sortby=="date"){
                f = params.fromDate; t = params.toDate
            }else {
                f = Invoker.GetDateTime("-1"); t = Invoker.GetDateTime();
            }
            url = testurl ? _LSIURL + '/api/v1/transaction//search?_json={"seller_id":'+_user_id+',"transaction_state_code":["ABORP","ABORB","ABORS"],"_count" : "1",'+
            '"_select":["transaction_state_code","title","auction_id","transaction_id","auction.size_classification","tracking_id","auction.address_name","state_change_time","auction.address_id","amount","auction.close_time","auction.reference_notes"]'+
            ',"_page" : '+ (params.page || 1) +' , "_per_page" : '+ (params.per_page || CONFIG.DEFAULT_PAGESIZE) +', "state_change_time>": "'+f+'", "state_change_time<": "'+t+'" }' : "../data/cancelledreports.json?";
            break;
        case "inprogress":
            if(params.sortby=="date"){
                f = params.fromDate; t = params.toDate
            }else {
                f = Invoker.GetDateTime("-1"); t = Invoker.GetDateTime();
            }
            url = testurl ? _LSIURL + '/api/v1/transaction//search?_json={"seller_id":'+_user_id+',"transaction_state_code":["APPRV","BPAY","CARR","DISIT","NEED","PSELL","QUOT","RSHP","SHIP"],"_count" : "1",'+
            '"_select":["transaction_state_code","title","auction_id","transaction_id","auction.size_classification","tracking_id","auction.address_name","state_change_time","auction.address_id","amount","auction.close_time","auction.reference_notes"]'+
            ',"_page" : '+ (params.page || 1) +' , "_per_page" : '+ (params.per_page || CONFIG.DEFAULT_PAGESIZE) +', "state_change_time>": "'+f+'", "state_change_time<": "'+t+'"}' : "../data/cancelledreports.json?";
            break;
        case "all":
            if(params.sortby=="date"){
                f = params.fromDate; t = params.toDate
            }else {
                f = Invoker.GetDateTime("-1"); t = Invoker.GetDateTime();
            }
            url = testurl ? _LSIURL + '/api/v1/auction//search?_json={"user_id":'+_user_id+',"record_status":["AC","S","RW","AO","PHO","W2","A","DE","SR","SV","P","CS","D","RV","R","CON"],"_count":"1","_select":["current_bid","title","auction_id","transaction_id","creation_time","tracking_id","address_name","category","reference_notes","open_time","close_time","size_classification","previous_auction_id","record_status","state_change_time"], "_sort":"close_time", "close_time>":"'+f+'" , "close_time<": "'+t+'", "_page" : '+ (params.page || 1) +' , "_per_page" : '+ (params.per_page || CONFIG.DEFAULT_PAGESIZE) +'}':  "../data/activeauctions.json?";
            break;
    }
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        success: function(data) { 
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Retrieve Active Auctions Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetPhotoUploadUrl = function() { 
    return (testurl) ? "/api/v1/image//create" : "unused/upload.html";
}

Invoker.GetImageData = function(request, callback) {
    var url = testurl ? _LSIURL + request.uri + "?_select=slideshow_order&_select=auction_id&_select=title&_select=path&_select=name&_select=status"
    : "../data/image_after_upload.js?GetImageData" ;
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Unable to get Image data ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetAllImages = function(request, callback) {
    var url = testurl ? _LSIURL + "/api/v1/image//search?auction_id=" + request.auction_id + "&user_id="+_user_id + "&slideshow_order%3E=-1" + "&_select=image_id&_select=status&_select=name&_select=title&_select=path&_select=slideshow_order&_sort=%2Bslideshow_order&status=A&_per_page=1000"
    : "../data/image_after_upload.js?GetAllImages" ;
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Unable to get Image data ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.UpdateImage = function(request, params, callback) {
    var url = testurl ? _LSIURL + request.uri+"/update" : "../data/image_after_upload.js?UpdateImage";
    $.ajax({
        type:"POST", 
        url: url,
        cache: false,
        data: params,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Update Image Failure ", XMLHttpRequest, textStatus, errorThrown);
        // callback(errorThrown,false);
        }
    });
}

Invoker.DeleteImage = function(request, callback) {
    var url = testurl ? _LSIURL + request.uri+"/update"  : "../data/image_after_upload.js?DeleteImage";
    $.ajax({
        type:"POST",
        url: url,
        data: "status=TR",
        dataType : "json",
        success: function(data){
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Delete Image Failure", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetUserInfo = function(params, callback) {
    var qs = Invoker.hashToQuery(params);
    var url = _LSIURL + "/api/v1/user//search?username=" + _username + "&" + qs;
    $.getScript(url + "&_jsonp=" + callback);
}

Invoker.setUserId = function(callback) {
		var url = (testurl) ? _LSIURL + "/api/v1/user//identify"+"?_select=signed_asa_time&_select=default_inventory_fields"
    : "../data/userdata.json";
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() {
            if ($.cookie('username') == null || !navigator.cookieEnabled) {
                //Info.Show.errorMsg("Cookies disabled. Please log back!");
                alert("It seems you are not logged in. Redirecting to login screen.");
                window.location.href = _LSI_LOGIN;
                return false;

            } else return true;
        },
        success: function(data) {
            if(data.result){
                _user_id = (testurl) ? data.result.user.id : "117355";
                _seller_name = (data.result && data.result.username) ? data.result.username : "&nbsp;";
                _asa_time = (data.result && data.result.signed_asa_time) ? data.result.signed_asa_time : null;
                _default_inventory_fields = (data.result && data.result.default_inventory_fields) ? data.result.default_inventory_fields : null;

                callback(_user_id, true);
            } else if(data.error && data.error[0]){
                alert(data.error[0].error_text);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // Invoker.GetErrorMessage("Unable to get User details ", XMLHttpRequest, textStatus, errorThrown);
            alert("It seems you are not logged in. Redirecting to login screen.  (" +errorThrown+ ") then ("+textStatus+")");
            window.location.href = _LSI_LOGIN;
        }
    });
}

Invoker.GetAccessResource = function(callback) {
    var url = testurl ? _LSIURL + "/api/v1/access//check?rule=dashboard&rule=createauction&rule=duplicateauctions&rule=actionreq&rule=bulkauctions&rule=savedauction&rule=shippinginfo&rule=reports&rule=sellerkpi"
    : "../data/useraccess.json";
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) { 
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Unable to get User Access data ", XMLHttpRequest, textStatus, errorThrown);
        // callback(errorThrown,false);
        }
    });
}

Invoker.GetUserMultiInventoryFields = function(callback){
    var url = testurl ? _LSIURL + "/api/v1/user/" + _user_id + "?_select=default_multi_inventory_fields" : "../data/multiinventory.json";
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("GetUserMultiInventoryFields ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetUserDefaultInventoryFields = function() {
    try {
        if ($.cookie('username') != null) {
            return (_default_inventory_fields != null) ? _default_inventory_fields.split(",") : ["description","quantity","retail_price"] ;
        } else {
            Info.Show.errorMsg("Cookies disabled. Please log back");
            return false;
        }
    } catch(e) {
        Info.Show.errorMsg("Invoker.GetASAContract " + e);
        return false;
    }
}

Invoker.SetUserDefaultInventoryFields = function(params, callback) {
    try {
        var url = (testurl) ? _LSIURL + "/api/v1/user/" + _user_id + "/update"
        : "../data/data_InventoryDefault.js?SetUserDefaultInventoryFields";
        $.ajax({
            type:"POST",
            url: url,
            cache: false,
            data: "default_inventory_fields=" + params,
            beforeSend: function() { 
                return Invoker.ValidateCookie();
            },
            success: function(data) {
                callback(data);
                url = (testurl) ? _LSIURL + "/api/v1/user/" + _user_id + "?_select=default_inventory_fields" : "../data/sample_metadata.js?SetUserID";
                $.ajax({
                    type:"GET",
                    url: url,
                    cache: false,
                    dataType : "json",
                    success: function(data) {
                        _default_inventory_fields = (data.result && data.result[0].default_inventory_fields) ? data.result[0].default_inventory_fields : null;
                    //true value returned for success
                    //callback(_user_id, true);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        Invoker.GetErrorMessage("Unable to get User details ", XMLHttpRequest, textStatus, errorThrown);
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                Invoker.GetErrorMessage("Invoker.SetUserDefaultInventoryFields",
                    XMLHttpRequest, textStatus, errorThrown)
            }
        });
    } catch(e) {
        Info.Show.errorMsg("Invoker.SetUserDefaultInventoryFields " + e);
    }
}

Invoker.GetSpreadSheetUploadUrl = function() {
    if ($.cookie('username') != null) {
        var url = (testurl) ? _LSIURL + "/api/v1/spreadsheet//parse" : "unused/spreadsheet.html";
        return url;
    } else {
        Info.Show.errorMsg("Cookies disabled. Please log back");
        return false;
    }
}

Invoker.CreateSpreadsheetUrl = function() {
    if ($.cookie('username') != null)  return _LSIURL + "/api/v1/spreadsheet//create";
    else {
        Info.Show.errorMsg("Cookies disabled. Please log back");
        return false;
    }
}

/* Get pending questions from buyers
 * 1)This request gives all the blank answers for that seller, but some of those blank answers have questions that
don't need to be answered, either because they've been deleted or they haven't yet been approved
 * 2) take the qna_id for each blank answer, and lookup the question, you'll be able to determine which of those need answering
 * 3) if you get a record, then that question needs answering
 *    if you don't, it means the record_status of the question is not A, and therefore doesn' tneed answering
 * */
Invoker.GetActionRequiredAuction = function(param, callback) {
    var url = _LSIURL + "/api/v1/action_required//search?user_id=" + _user_id +
    "&record_status=A&_select=type&_select=auction_address_id" +
    "&_select=auction_title&_select=auction_id" +
    "&_select=transaction_id&_select=record_status" +
    "&_select=resource_updated_time&_select=auction_category" +
    "&_select=auction_address_name&_select=auction_reference_notes" +
    "&_select=auction_current_bid&_select=target_uri&_select=auction_status" +
    "&_select=question&_select=dispute_reason_code&_count=1" +
    "&"+param.filterby+"="+param.filtervalue +
    "&_page=" + (param.page || 1) +
    "&_per_page=" + (param.per_page || CONFIG.DEFAULT_PAGESIZE) ;
    if(param.searchby)url += "&"+param.searchby+"="+param.searchvalue;
    if(param.sortby) {
        if(param.sortby=="flag")url += "&_sort="+param.sortorder; //"&"+param.sortorder+"=1";
        else if(param.sortby=="date")url += "&resource_updated_time>=" + param.fromDate + "&resource_updated_time<=" + param.toDate +"&_sort=%2Bresource_updated_time";
        else url += "&_sort="+(param.sortorder ? "%2B" : "-")+""+param.sortby;
    } else url += "&_sort=-urgent_flag"; //url += "&_sort=%2Bresource_updated_time";
    
    
    url = testurl ? url : "../data/action_required.json"
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("GetActionRequiredAuction ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetPreviousLabels = function(param, callback){
    var url = testurl ? _LSIURL + "/api/v1/transaction//search?seller_id="+_user_id+"&transaction_state_code=CARR&shipment.label_printed_time>=0&_select=shipment.label_printed_time&_select=title&_select=auction.address_name&_select=auction_id&_select=transaction_id&_select=auction.size_classification&_select=auction.record_status&_select=auction.reference_notes&_count=1"+
    "&"+param.filterby+"="+param.filtervalue +
    "&_page=" + (param.page || 1) +
    "&_per_page=" + (param.per_page || CONFIG.DEFAULT_PAGESIZE)
    : "../data/reprintlabels.json";
    if(param.searchby)url += "&"+param.searchby+"="+param.searchvalue;
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",

        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) { 
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Invoker.GetPreviousLabels failed ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetPrintShippingURL = function(request, callback) {
    var url;
    if(request.uri){
        url = testurl ? _LSIURL + request.uri+"?_select=label_image_urls" : "../data/imagelabel.json";
    }else if(request.transaction_id){
        url = testurl ? _LSIURL +'/api/v1/transaction//search?_json={"seller_id":'+_user_id+',"transaction_id":['+request.transaction_id+'],"_select":"label_image_urls"}' : "../data/multiple_printlabels.json";
    }
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) { 
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("GetPrintShippingURL ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.UpdateActionRequiredData = function(request, params, callback) {
    var url = null;
    var title = Invoker.GetTransactionStatusLexicon(request.type);
    if (request.type == "QNA") {
        url = _LSIURL + request.uri+"/update";
        $.ajax({
            type:"POST",
            url: url,
            data : params,
            dataType: "json",
            success: function(data) {
                // Update a completed action by setting record_status=D
                if (data.result && data.result[0] && data.result[0].qna) {
                    url = _LSIURL + request.action_required_uri + "/update";
                    $.ajax({
                        type:"post",
                        url: url,
                        data: "record_status=D",
                        dataType: "json",
                        success: function(data) { 
                            callback(data, request.type, title); 
                            //Update the alert component
                            AlertBar.RenderAlertBar("subMenu");
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            Invoker.GetErrorMessage(title+" Failure ", XMLHttpRequest, textStatus, errorThrown)
                        }
                    });
                } else if(data.error && data.error[0]) callback(data, request.type, title);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                Invoker.GetErrorMessage(title+" Failure ", XMLHttpRequest, textStatus, errorThrown)
            }
        });
    }else if (request.type == "TNP" || request.type == "RTNP") {
        url = _LSIURL + request.uri+"/printlabel";
        $.ajax({
            type:"POST",
            url: url,
            data : params,
            dataType: "json",
            success: function(data) {
                //                  Update a completed action by setting record_status=D
                if (data.result && data.result[0] && data.result[0].transaction) {
                    if(request.type == "TNP"){// do not update action required data for re-print label
                        url = testurl ? _LSIURL + request.action_required_uri + "/update" : "../data/imagelabel.json";
                        $.ajax({
                            type:"post",
                            url: url,
                            data: "record_status=D",
                            dataType: "json",
                            success: function(data) { 
                                callback(data); 
                                //Update the alert component
                                AlertBar.RenderAlertBar("subMenu");
                            },
                            error: function(XMLHttpRequest, textStatus, errorThrown) {
                                Invoker.GetErrorMessage(title+" Failure ", XMLHttpRequest, textStatus, errorThrown)
                            }
                        });
                    } else  callback(data);
                } else if(data.error && data.error[0]) Info.Show.errorMsg(data.error[0].error_text);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                Invoker.GetErrorMessage(title+" Failure ", XMLHttpRequest, textStatus, errorThrown)
            }
        });
    }else if (request.type == "DISIT") {
        //                 // Update a completed action by setting record_status=D
        url = _LSIURL + request.action_required_uri + "/update";
        $.ajax({
            type:"post",
            url: url,
            data: "record_status=D",
            dataType: "json",
            success: function(data) {
                callback(data, request.type, title); 
                //Update the alert component
                AlertBar.RenderAlertBar("subMenu");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                Invoker.GetErrorMessage(title+" Failure ", XMLHttpRequest, textStatus, errorThrown)
            }
        });
    }
}
// support method for Dispute updates
Invoker.GetDisputeURL = function(request){
    return _LSIURL + request.uri+"/respond";
}
Invoker.GetAuctionMetadata = function(params, callback) {
    if (params == "category")
        callback(__CATEGORY_AND_SUBCATEORY);
    else if (params == "country")
        callback(__COUNTRY_CODE);
    else if (params == "state")
        callback(__STATE_CODE);
    else if(params == "condition")
        callback(Invoker.GetCondition());

}

Invoker.CreateBasicAuction = function(params, callback) {
    var url = (testurl) ? _LSIURL + "/api/v1/auction//create" : "../data/sample_metadata.js?CreateBasicAuction";
    params.user_id = _user_id;
    params.category_id = params.category_id.split(",");
    $.ajax({
        type:"POST",
        url: url,
        data:params,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            data = (testurl) ? data : {
                'result': [ {
                    'auction': {
                        'id': '117355',
                        'uri': '/api/v1/auction/117355'
                    }
                } ]
            };
            Invoker.PrepareCallback(data,callback);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Create Basic Auction Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.CreateMultiAuction = function(params, callback) {
    var url = (testurl) ? _LSIURL + "/api/v1/auction//create" : "../data/sample_metadata.js?CreateBasicAuction";
    $.ajax({
        type:"POST",
        url: url,
        data: "_json=" + params,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback((testurl) ? data : {
                'result': [ {
                    'auction': {
                        'id': '117355',
                        'uri': '/api/v1/auction/117355'
                    }
                } ]
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Create Basic Auction Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetSavedMultiAuction = function(request, callback) {
    var url = (testurl) ? _LSIURL + request.uri + "?record_status=SV&_select=title&_select=reference_notes&_select=creation_time&_select=category&_select=photo_count&_select=item_count&_select=address_name&_select=missingdata&_select=size_classification" : "../data/multiauction.json?GetSavedMultiAuction";
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            if(data.result && data.result.length > 0){
                callback(data);
            }
            else  if (data.result && data.result.length == 0){
                // return the id, if the record not available. Case: after submit, when the user press back button, inorder to get the record id
                var id = request.uri.split("/");
                id = id[id.length - 1];
                callback(data,id);
            }else if(data.error && data.error[0]){ 
                Info.Show.errorMsg(data.error[0].error_text);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Get Saved Auction Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.UpdateAuctionDetails = function(request, params, callback) {
    var url = testurl ? _LSIURL + request.uri + "/update" : "../data/updateauction.json";
    params.category_id = params.category_id.split(",");
    // Since the number_of_boxes is a list box and by default it is set as 1. unless the user sets the size classification, do not update the code
    //    if(!params.size_classification)params["number_of_boxes"]=undefined;
    if(params.size_classification!="PACK"){
        if(params.weight)params.weight = ""; if(params.length)params.length = ""; if(params.width)params.width = ""; if(params.height)params.height = "";
    }
    $.ajax({
        type:"POST",
        url: url,
        data: params ,
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            if(request.type=="ANR"){
                url =  testurl ? _LSIURL + request.action_required_uri + "/update" : "../data/updateauction.json";
                $.ajax({
                    type:"post",
                    url: url,
                    data: "record_status=D",
                    dataType: "json",
                    success: function(data) { 
                        Invoker.PrepareCallback(data,callback); 
                        //Update the alert component
                        AlertBar.RenderAlertBar("subMenu");
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        Invoker.GetErrorMessage(title+" Failure ", XMLHttpRequest, textStatus, errorThrown)
                    }
                });
            }else Invoker.PrepareCallback(data,callback);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Update Auction Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
Invoker.GetAuctionPreviewUrl = function() {
    if ($.cookie('username') != null) {
        var url = "auctionpreview.html";
        return url;
    } else {
        Info.Show.errorMsg("Cookies disabled. Please log back");
        return null;
    }
}

Invoker.GetAllAuctionItems = function(auction_id, callback,param) {
    if(param){
        if(param.fields){
            var queryString = Invoker.hashToQuery(param.fields);
            var url = testurl ? _LSIURL + "/api/v1/auction_item//search?auction_id=" + auction_id + "&user_id="+_user_id +
            "&record_status=A&"+queryString + "&_count=1&_page=" + (param.page || 1) + "&_per_page=" + (param.per_page || CONFIG.DEFAULT_PAGESIZE) : "../data/auction_items.json" ;
        }else{
            url = testurl ? _LSIURL + "/api/v1/auction_item//search?auction_id=" + auction_id + "&user_id="+_user_id +
            "&record_status=A&_select=serial_number&_select=retail_price&_select=record_status&_select=uom&_select=auction_id&_select=model&_select=size&_select=expected_condition"+
            "&_select=color&_select=ext_retail_price&_select=auction_items_detail_id&_select=creation_time&_select=model_number&_select=cost&_select=upc_code"+
            "&_select=make&_select=ext_cost&_select=quantity&_select=description&_select=comment&_select=item_pkg_weight&_select=product_category"+
            "&_select=country_of_manufacture&_select=item_pkg_weight_unit&_select=year&_select=season&_count=1"+
            "&_page=" + (param.page || 1) + "&_per_page=" + (param.per_page || CONFIG.DEFAULT_PAGESIZE): "../data/auction_items.json" ;
        }
    }
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) { 
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Unable to get Auction Items data ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.getAuctionItemsCount = function(auction_id,callback){
    var url = testurl ? _LSIURL + "/api/v1/auction_item//search?auction_id=" + auction_id + "&user_id="+_user_id + "&_per_page=9999"+
    "&record_status=A&_count=1": "../data/auction_items.json" ;
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) { 
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Unable to get Auction Item data ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.CreateAuctionItem = function(auction_id, params, callback) {
    var url = testurl ? _LSIURL + "/api/v1/auction_item//create" : "../data/auction_items.json";
    params.items[0].auction_id = auction_id;
    $.ajax({
        type:"POST", 
        url: url,
        cache: false,
        data: params.items[0],
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) { 
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Create Auction Item(s) Failure ", XMLHttpRequest, textStatus, errorThrown);
            var data = {
                "result" : [],
                "error" : [{
                    "status_code": textStatus,
                    "message" : "Create Auction Item(s) Failure"
                }]
            };
            callback(data)
        }
    });
}
Invoker.CreateMultipleAuctionItem = function(dataObj,callBackData,callback) {
    var url = testurl ? _LSIURL + "/api/v1/auction_item//create_multiple"  : "../data/delMultiple.json";
    $.ajax({
        type:"POST",
        url: url,
        data: "_json="+encodeURIComponent(dataObj),
        dataType : "json",
        success: function(data){
            callback(callBackData,data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Create Auction Item(s) Failure ", XMLHttpRequest, textStatus, errorThrown);
            var data = {
                "result" : [],
                "error" : [{
                    "status_code": textStatus,
                    "message" : "Create Auction Item(s) Failure"
                }]
            };
            callback(data)
        }
    });
}

Invoker.UpdateAuctionItem = function(uri, params, callback) {
    var url = testurl ? _LSIURL + uri + "/update" : "../data/auction_items.json";
    $.ajax({
        type:"POST",
        url: url,
        data: params.items[0],
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) { 
            if (data.result && data.result[0])callback(data);
            else if(data.error && data.error[0]) {
                Info.Show.errorMsg(data.error[0].error_text); 
                callback(data);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Update Auction Item(s) Failure ", XMLHttpRequest, textStatus, errorThrown);
            var data = {
                "result" : [],
                "error" : [{
                    "status_code": textStatus,
                    "message" : "Update Auction Item(s) Failure",
                    "error_text" : "Update Auction Item(s) Failure"
                }]
            };
            callback(data)
        }
    });
}

Invoker.DeleteAuctionItem = function(uri, callback) {
    var url = testurl ? _LSIURL + uri+"/update"  : "../data/image_after_upload.js?DeleteImage";
    $.ajax({
        type:"POST",
        url: url,
        data: "record_status=D",
        dataType : "json",
        success: function(data){
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Delete Auction Item Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
Invoker.UpdateMultipleAuctionItems = function(dataObj,callBackData,callback) {
    var url = testurl ? _LSIURL + "/api/v1/auction_item//update_multiple"  : "../data/delMultiple.json";
    $.ajax({
        type:"POST",
        url: url,
        //fix for the &@#$^@#%%@# etc
        data: "_json="+encodeURIComponent(dataObj),
        dataType : "json",
        success: function(data){
            callback(callBackData,data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Delete Auction Item Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
Invoker.SubmitAuctions = function(request, params, callback) {
    params.user_id = _user_id;
    var response = {
        "result": [],
        "error" : []
    };
    var url = (testurl) ? _LSIURL + request.uri + "/submit" : "../data/updateauction.json";
    $.ajax({
        type:"POST",
        url: url,
        data: params,
        dataType: "json",
        beforeSend: function() {
            if(Invoker.ValidateCookie() && _asa_time!=null && _asa_time!="") return true ;
            else {
                //todo api error message should be captured somehow instead of hardcoding the error text
                Info.Show.actionRequiredMsg(_asa_text);
                pageUnblock();
                return false;
            }
        },
        success: function(data) {
            if(data.error && data.error[0]) {
                Info.Show.errorMsg(data.error[0].error_text);
            }else if(data.result && data.result[0]) {
                if(request.type=="ANR"){
                    url = (testurl) ? _LSIURL + request.action_required_uri + "/update" : "../data/updateauction.json";
                    $.ajax({
                        type:"post",
                        url: url,
                        data: "record_status=D",
                        dataType: "json",
                        success: function(data) { 
                            callback(data);
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            Invoker.GetErrorMessage(title+" Failure ", XMLHttpRequest, textStatus, errorThrown)
                        }
                    });
                }else callback(data);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            response.error.push({
                "xmlhttprequest" : XMLHttpRequest,
                "textStatus" : textStatus,
                "errorThrown" : errorThrown
            });
            Invoker.GetErrorMessage("Submit auction failure ", XMLHttpRequest, textStatus, errorThrown);
            callback(response, false);
        }
    });
}

Invoker.SDAuctions = function(type, request, passback, callback){
    var response = {
        "result": [],
        "error" : []
    };
    url = (testurl) ? ((type=="delete")? _LSIURL + request.auction.uri + "/delete" : _LSIURL + request.auction.uri + "/submit") : "../data/sample_metadata.js?DeleteAuctions";
    $.ajax({
        type:"POST",
        url: url,
        data: "",
        dataType: "json",
        success: function(data) {
            if(data.error && data.error[0]) {
                Info.Show.errorMsg(data.error[0].error_text);
                callback(passback,false,data.error[0]);
            }else if(data.result && data.result[0]) {
                callback(passback,true,data.result[0]);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            response.error.push({
                "xmlhttprequest" : XMLHttpRequest,
                "textStatus" : textStatus,
                "errorThrown" : errorThrown
            });
            callback(passback,false, response.error[0]);
        }
    });
}

Invoker.GetInventoryFields = function(callback) {
    var url = testurl ? _LSIURL + "/api/v1/auction//inventory_fields" : "../data/inventory.json?GetInventoryFields" ;
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Unable to Get Inventory List ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
/* Saved, Submitted, Active */
Invoker.GetAuctionsForDuplicate = function(param, callback) {
    var url = _LSIURL + "/api/v1/auction//search?user_id=" + _user_id + "&_select=record_status";
    if(param.searchby && param.searchby=="auction")url+="&record_status="+param.searchvalue; 
    else url+="&record_status=SV&record_status=A"; //record_status=S&
   
    url+= Invoker.GetQueryForRetrievingAuctionDetails()+
    "&_sort=-creation_time"+
    "&_page=" + (param.page || 1) +
    "&_per_page=" + (param.per_page || CONFIG.DEFAULT_PAGESIZE);
    if(param.searchby && param.searchby!="auction")url += "&"+param.searchby+"="+param.searchvalue;
    else if(param.sortby) {
        if(param.sortby=="flag")url += "&"+param.sortorder+"=1";
        else if(param.sortby=="date")url += "&creation_time>=" + param.fromDate + "&creation_time<=" + param.toDate;
        else url += "&_sort="+(param.sortorder ? "%2B" : "-")+""+param.sortby;
    }
    url = testurl ? url : "../data/savedauction.json?GetSavedAuction"
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        beforeSend: function() {
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Copy Existing Auctions ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
        
Invoker.GetSavedAuction = function(param, callback) {
    var url = _LSIURL + "/api/v1/auction//search?user_id=" + _user_id +
    "&record_status=SV" +
    Invoker.GetQueryForRetrievingAuctionDetails()+
    "&_page=" + (param.page || 1) +
    "&_per_page=" + (param.per_page || CONFIG.DEFAULT_PAGESIZE)  ;
    if(param.searchby)url += "&"+param.searchby+"="+param.searchvalue;
    else if(param.sortby) {
        if(param.sortby=="flag")url += "&"+param.sortorder+"=1";
        else if(param.sortby=="date")url += "&creation_time>=" + param.fromDate + "&creation_time<=" + param.toDate;
        else url += "&_sort="+(param.sortorder ? "%2B" : "-")+""+param.sortby;
    }else url += "&_sort=-creation_time";
    if(param.auction_id)url += "&auction_id="+param.auction_id; // added inorder to get auction details after edit/submit/save. Used in duplicates/saved auction
    url = testurl ? url : "../data/savedauction.json?GetSavedAuction"
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        beforeSend: function() {
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Get Saved Auction ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
        
Invoker.DuplicateAuction = function(request, oObj, callback) {
    var url = testurl ? _LSIURL + request.uri + "/duplicate" : "../data/savedauction.json?DuplicateAuction";
    $.ajax({
        type:"POST",
        url: url,
        data: "copies=" + request.copies,
        dataType : "json",
        beforeSend: function() {
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            if(data.result && data.result.length>0){
                $.ajax({
                    type:"GET",
                    url: _LSIURL +data.result[0].auction.uri+"?_select=creation_time",
                    cache: false,
                    dataType: "json",
                    success: function(pData) {
                        oObj.creation_time = pData.result[0].creation_time;
                        callback(data,oObj);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        Invoker.GetErrorMessage("Get Creation time ", XMLHttpRequest, textStatus, errorThrown);
                    }
                });
            } else callback(data,oObj);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            //                    Invoker.GetErrorMessage("Duplicate Auction Failure", XMLHttpRequest, textStatus, errorThrown);
            // getting microsoft http error 12152 in ie
            callback({
                "error":[ {
                    "error_text": "Duplicate Auction Failure. Try after some time"
                }]
            },oObj);
        }
    });
}
        
Invoker.GetAuctionDetails = function(request, callback) {
    var url = testurl ?  _LSIURL +request.uri+
    "?_select=title&_select=reference_notes&_select=creation_time&_select=close_time&_select=open_time" +
    "&_select=category&_select=size_classification&_select=current_bid&_select=auction_shipping.shipping_restriction_code"+
    "&_select=description&_select=length&_select=height&_select=width&_select=auction_shipping.weight_unit_code"+
    "&_select=weight&_select=number_of_boxes&_select=number_of_pallets"+
    "&_select=pallet_weight&_select=revision_notes&_select=notes_to_lsi&_select=photo_count&_select=auction_shipping.pallet_weight_unit_code" +
    "&_select=username&_select=user_id&_select=record_status&_select=items&_select=condition_code" +
    "&_select=auction_id&_select=state_change_time&_select=signed_sch1_time&_select=auction_shipping.dim_unit_code&_select=original_platform_id"+
    "&_select=item_count&_select=missingdata&_select=auction_shipping.shipping_organization&_select=address_id&_select=address_name&_select=original_description&_select=country_origin_code"+
    "&_select=retail_price_url1&_select=retail_price_url2&_select=retail_price_url3&_select=country_origin_code&_count=1"
    : "../data/sampleauctiondata.json";
    var _tJson = {
        "result" : [],
        "error" : []
    };
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType : "json",
        beforeSend: function() {
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            if(data.result && data.result[0]){
                _tJson.result.push(data.result[0]);
                if(data.result[0].address_id && data.result[0].address_id!="0" && data.result[0].address_id!=null){
                    url = testurl ? _LSIURL +"/api/v1/address/"+data.result[0].address_id+"?_select=name&_select=country_code&_select=state&_select=postal_code": "../data/sampleauctiondata.json";
                    $.ajax({
                        type:"GET",
                        url: url,
                        cache: false,
                        dataType : "json",
                        success: function(data) {
                            if(!testurl)data = {
                                "prev_page_uri":null,
                                "page":"1",
                                "per_page":30,
                                "next_page_uri":null,
                                "result":[{
                                    "postal_code":"666666",
                                    "name":"Waste Mart",
                                    "address":{
                                        "id":"3430265",
                                        "uri":"/api/v1/address/3430265"
                                    },
                                    "state":"HI",
                                    "country_code":"US"
                                }]
                            };
                            if(data.result && data.result[0]){
                                _tJson.result.push(data.result[0]);
                                callback(_tJson);
                            }else if(data.error && data.error[0]) {
                                Info.Show.errorMsg(data.error[0].error_text);
                                callback(_tJson);
                            }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            Invoker.GetErrorMessage("Get Shipping Details Failure ", XMLHttpRequest, textStatus, errorThrown);
                            _tJson.result.push(data.result[0]);
                            callback(_tJson);
                        }
                    });
                } else callback(_tJson);
            }else if(data.error && data.error[0]){
                Info.Show.errorMsg(data.error[0].error_text);
                _tJson.result.push(data.error[0]);
                callback(_tJson);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Get Auction Details Failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

Invoker.GetAlerts = function (callback) {
    var url = testurl ? _LSIURL+"/api/v1/action_required//quickcounts" : "../data/alerts.json";
    _json_data = { 
        'result': [ ]
    };
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        success: function(data) {
            if(data.result[0].QNA){
                _json_data.result.push({
                    name : Invoker.GetTransactionStatusLexicon("QNA"),
                    count : data.result[0].QNA,
                    new_count : (data.result[0].QNA_new) ? ", "+data.result[0].QNA_new+" new" : "",
                    select : 'QNA',
                    classname  : 'questionIcon'
                });
            }
            if(data.result[0].DISIT){
                _json_data.result.push({
                    name : Invoker.GetTransactionStatusLexicon("DISIT") ,
                    count : data.result[0].DISIT,
                    new_count : (data.result[0].DISIT_new) ? ", "+data.result[0].DISIT_new+" new" : "",
                    select : 'DISIT',
                    classname  : 'disputeIcon'
                });
            }
            if(data.result[0].TNP){//data.result[0].QNA
                _json_data.result.push({
                    name : Invoker.GetTransactionStatusLexicon("TNP") ,
                    count : data.result[0].TNP,
                    new_count : (data.result[0].TNP_new) ? ", "+data.result[0].TNP_new+" new" : "",
                    select : 'TNP',
                    classname  : 'shippingIcon'
                });
            }
            if(data.result[0].CARR){
                _json_data.result.push({
                    name : Invoker.GetTransactionStatusLexicon("CARR") ,
                    count : data.result[0].CARR,
                    new_count : (data.result[0].CARR_new) ? ", "+data.result[0].CARR_new+" new" : "",
                    select : 'CARR',
                    classname  : 'prepareIcon'
                });
            }
            if(data.result[0].ANR){
                _json_data.result.push({
                    name : Invoker.GetTransactionStatusLexicon("ANR"),
                    count : data.result[0].ANR,
                    new_count : (data.result[0].ANR_new) ? ", "+data.result[0].ANR_new+" new" : "",
                    select : 'ANR',
                    classname  : 'revisionIcon'
                });
            }
            callback(_json_data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Get Alerts failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
                    
/*
 * Usage :
 * To retrieve Billing address, use Invoker.GetShippingAddress(callback, "billing");
 * To retrieve Shipping address (tabel view), use Invoker.GetShippingAddress(callback, "table");
 * To retrieve Shipping address (Selectbox view), use Invoker.GetShippingAddress(callback);
 */
Invoker.GetShippingAddress = function(callback) {
    var url = "";
    var args = Invoker.GetShippingAddress.arguments;
    if (args[1] && args[1] == "table")
        url = _LSIURL + "/api/v1/address//search?user_id=" + _user_id + "&record_status=A&_select=name&_select=address1&_select=address2&_select=city&_select=state&_select=postal_code&_select=country_code&_select=contact_fname&_select=contact_lname&_select=company&_select=creation_time&_select=default_shipping_location_flag&_select=ups_daily_pickup_flag&address.address_type=SHIP&_select=statetext&_per_page=100";
    else
        url = _LSIURL + "/api/v1/address//search?user_id=" + _user_id + "&record_status=A&_select=name&address.address_type=SHIP&_select=default_shipping_location_flag&_per_page=100";
    url = (testurl) ? url : "../data/datamanageshipping.js?GetShippingAddress";
    $.ajax({
        type:"GET",
        url: url,
        cache: false,
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Invoker.GetErrorMessage("Get shipping address failure ", XMLHttpRequest, textStatus, errorThrown);
        }
    });
}
Invoker.GetShippingAddressTableView = function(callback) {
    Invoker.GetShippingAddress(callback, "table");
}
Invoker.AddNewShippingAddress = function(params, callback) {
    var qs = Invoker.hashToQuery(params);
    var url = _LSIURL + "/api/v1/address//create";
    $.ajax({
        type:"POST",
        url: url,
        data: "user_id=" + _user_id + "&" + qs,
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {  
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Info.pShow.errorMsg("Create Shipping Failure. Please try after some time.");
        }
    });
}
                    
Invoker.UpdateShippingAddress = function(uri, params, callback) {
    var url = _LSIURL + uri + "/update";
    var id = uri.split("/");
    id = id[id.length - 1];
    $.ajax({
        type:"POST",
        url: url,
        data: params,
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Info.pShow.errorMsg("Update Shipping Failure "+ XMLHttpRequest + ": " + textStatus);
            $('#'+id+"process").hide();
        }
    });
}
Invoker.DeleteShippingAddress = function(uri, callback) {
    var url = _LSIURL + uri + "/update";
    $.ajax({
        type:"POST",
        url: url,
        data: "record_status=D",
        dataType: "json",
        beforeSend: function() { 
            return Invoker.ValidateCookie();
        },
        success: function(data) {
            callback(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Info.Show.errorMsg("Delete Shipping Failure "+ XMLHttpRequest + ": " + textStatus);
            var id = uri.split("/");
            id = id[id.length - 1];
            $('#'+id+"process").hide();
        }
    });
}
Invoker.GetActiveAuctionPreview = function(auction_id){
    return _LSIURL+"/auction/view?id="+auction_id;
}
                    
Invoker.hashToQuery = function(p) {
    var qs = ""; var j = 0;
    if (typeof(p) == "object") {
        for (k in p) {
            if ((k == "select" || k == "period_days" || k == "category_id") && (p[k]) && ((val = p[k].split(",")).length > 0)) {
                if (k == "select") k = "_select";
                for (j = 0; j < val.length; j++) { 
                    qs += k + "=" + val[j] + "&";
                }
            } else { 
                if (p[k])qs += k + "=" + p[k] + "&";
            }
        }
    }//remove extra '&' from the generated query string'
    var fixQs = ""; var params = qs.split("&");
    var ll = params.length - 2;
    for (j = 0; j < params.length - 1; j++) {
        if (j == ll)fixQs += params[j];
        else fixQs += params[j] + "&";
    } return fixQs;
}
                    
Invoker.GetDisputeStatus = function(k){
    switch (k) {
        case "OPN": k="Open"; break;
        case "BRET": k="Buyer Returning"; break;
        case "FREF": k="Full Refund"; break;
        case "PREF": k="Partial Refund"; break;
        case "INV": k="Investigate"; break;
        case "DND": k="Denied"; break;
        default: k= ""; break;
    }return k;
}
                    
Invoker.GetAuctionStatusLexicon = function(k) {
    switch (k) {
        case "P":   k = "Pending"; break;
        case "CS":  k = "CService"; break;
        case "W2":  k = "Warehouse Revision Needed"; break;
        case "PHO": k = "Photography"; break;
        case "S":   k = "Sales"; break;
        case "CON": k = "Consumer Sales"; break;
        case "SR":  k = "Ship Review"; break;
        case "AC":  k = "Advertising"; break;
        case "R":   k = "Review"; break;
        case "A":   k = "Active"; break;
        case "D":   k = "Declined"; break;
        case "AO":  k = "Active Offline"; break;
        case "RW":  k = "Returns-Warehouse Revision"; break;
        case "DE":  k = "Deleted"; break;
        case "SV":  k = "Saved (Seller)"; break;
        case "RV": k = "Revision (Seller)"; break;
        default: k = ""; break;
    }return k;
}
                    
Invoker.GetTransactionStatusLexicon = function(k) {
    switch (k) {
        case "RSHP": k = "Goods ready to ship"; break;
        case "NO_PR": k = "GL: Creditcard pending"; break;
        case "CC_DE": k = "GL: Creditcard declined"; break;
        case "PSELL": k = "Paying Seller"; break;
        case "ABORB": k = "Cancel - (BUYER)"; break;
        case "ABORT": k = "Cancel - (LCOM)"; break;
        case "SHIP": k = "Goods in transit"; break;
        case "ADDR": k = "Waiting for Ship Address"; break;
        case "ABORS": k = "Cancel - (SELLER)"; break;
        case "APPRV": k = "Awaiting Approval"; break;
        case "DISBP": k = "Buyer Payment Dispute"; break;
        case "CC_AC": k = "GL: Creditcard accepted"; break;
        case "BPAY": k = "Waiting on Buyer to pay"; break;
        case "QUOT": k = "Waiting for Ship Quote"; break;
        case "BSHIP": k = "Buyer Arranging Shipping"; break;
        case "NEED": k = "Needs Admin attention"; break;
        case "TNP":   k = "Print Shipping Labels"; break;
        case "ANR":   k = "Auctions Needing Revision"; break;
        case "QNA":   k = "Questions from Buyers"; break;
        case "CARR":  k = "Prepare for Shipping"; break;
        case "COMPL": k = "Transaction complete"; break;
        case "DISIT": k = "Disputes Needing Attention"; break;
        case "INMAL": k = "Payment in transit"; break;
        case "PSELL": k = "Paying seller"; break;
        default: k = ""; break;
    } return k;
}
Invoker.GetCondition = function(){
    return { 
        result: [ {
            name: 'condition',
            value: {
                'NEW': 'New',
                'REFUR': 'Refurbished',
                'SHELF': 'Shelf Pulls',
                'USED': 'Used',
                'RET': 'Returns',
                'SCRAP': 'Salvage'
            }
        }]
    }
}
                    
Invoker.ValidateCookie = function() {
    if ($.cookie('username') == null && !navigator.cookieEnabled) {
        Info.Show.errorMsg("Cookies disabled. Please log back");
        window.location.href = _LSIURL+"/logout";
        return false;
    } else return true;
}
Invoker.GetErrorMessage = function(from, xmlhttprequest, textStatus, errorThrown) {
    pageUnblock();
    if (typeof(Info) != "undefined" && Info){
        if(xmlhttprequest.status!=0){    //avoid showing the error in FF when page reloads which means xmlhttprequest's status is 0 (uninitialized)
            Info.Show.errorMsg(from + " (" + xmlhttprequest.status + "). Try after some time");
        }
    }
    else window.location.href = _LSIURL;
}
Invoker.PrepareCallback = function(data,callback) {
    if (data.result && data.result[0])callback(data);
    else if(data.error && data.error[0]) {
        pageUnblock();Info.Show.errorMsg(data.error[0].error_text);
    }
}
Invoker.GetQueryForRetrievingAuctionDetails = function(){
    return "&_select=title&_select=reference_notes&_select=creation_time&_select=condition_code" +
    "&_select=category&_select=size_classification&_select=country"+
    "&_select=description&_select=length&_select=height&_select=width"+
    "&_select=weight&_select=number_of_boxes&_select=number_of_pallets"+
    "&_select=pallet_weight&_select=revision_notes&_select=notes_to_lsi&_select=photo_count" +
    "&_select=item_count&_select=missingdata&_select=address_name&_count=1" ;
}
Invoker.GetDateTime = function(k){
    var myDate = new Date(new Date().toUTCString());
    switch (k) {
        case "-1":
            k = ((myDate.getTime() + _default_reports_range*24*60*60*1000)/1000);
            break;
        default:
            k = (myDate.getTime()/1000);
            break;
    }
    return k;
}
                    
Invoker.GetManifestPreviewUrl = function(){ 
    var url = "previewmanifest.html"; return url;
}
Invoker.GetSlideShowUrl = function(){ 
    var url = "photoslideshow.html"; return url;
}

