﻿/* AJAX SETUP */
$().ready(function () {
    $.ajaxSetup({
        timeout: WS_TimeOut,
        error: function (x, e) {
            errorWS(x, e);
        }
    });
});

var UnitOfMesure = new Array('', '', 'box', 'case', 'cc', 'cl', 'cm', 'ct.', 'cubic in.', 'c.', 'ct.', 'fl. oz.', 'ft.', 'g', 'gal.', '', 'in.', 'kg', 'kit', 'lb.', 'liter', 'm', 'mg', 'ml', 'oz.', 'pc.', 'pkg.', 'pr.', 'pt.', 'qt.', 'set', 'sq. ft.', 'yd', 'bag');


function errorWS(x, e) {
    unlockScreen();
    if (e == 'timeout') {
        openMsg('Request Time out.', 5000);
        return;
    }
    
    if (x.status == 0) {
        openMsg('You are offline!!\n Please Check Your Network.', 5000);
    } else if (x.status == 404) {
        openMsg('Requested URL not found.', 5000);
    } else if (x.status == 500) {
        openMsg('Internel Server Error.', 5000);
    } else if (e == 'parsererror') {
        openMsg('Error.\nParsing JSON Request failed.', 5000);
    } else if (e == 'timeout') {
        openMsg('Request Time out.', 5000);
    } else {
        openMsg('Unknow Error.\n' + x.responseText, 5000);
    }
}

/* POPUP MESSAGE */
//openConfirmationMsg("Your Item has been successfully added to your list", 2000)
//openConfirmationMsg("", 2000)
//------  Show pop up message
function openMsg(sMsg, nTimeout) {

    if (sMsg == "")
    { sMsg = null }
    else
    { sMsg = "<div class='popupMSG'>" + sMsg + "</div>"; }

    $.blockUI({ message: sMsg, fadeIn: 300, fadeOut: 300, css: { left: '33%', border: 'none', width: '588px', height: '54px', background: 'url(app_themes/default/_images/alert_notify.gif)', color: '#fff' }, overlayCSS: { backgroundColor: '#000', opacity: 0.1, cursor: 'default'} });

    if (nTimeout != "undefined" && nTimeout != null)
        setTimeout(function () { $.unblockUI(); }, nTimeout);
};
function openMsg1(sMsg, nTimeout) {

    if (sMsg == "")
    { sMsg = null }
    else
    { sMsg = "<div class='popupMSG'>" + sMsg + "</div>"; }

    $.blockUI({ message: sMsg, fadeIn: 300, fadeOut: 300, css: { left: '33%', border: 'none', width: '588px', height: '54px', background: 'url(app_themes/default/_images/alert_notify.gif)', color: '#fff' }, overlayCSS: { backgroundColor: '#000', opacity: 0.0, cursor: 'default'} });

    if (nTimeout != "undefined" && nTimeout != null)
        setTimeout(function () { $.unblockUI(); }, nTimeout);
};
//------  Close pop up message
function closeMsg() {
    $.unblockUI();
};
//lock-Unlock screen
function lockScreen() {
    lockScreenWSpinner();
    //openMsg1("");
}
function unlockScreen() {
    $.unblockUI();
}
//<h3><img src="App_Themes/Default/_images/spinner.gif" /> Loading...</h3>
function lockScreenWSpinner(){
    $.blockUI({ message: '<div><img src="App_Themes/Default/_images/spinner.gif" /></div>', fadeIn: 300, fadeOut: 300, css: { left: '48%', border: 'none', width: '100px', height: '50px', allowTransparency: 'true', backgroundColor: 'transparent', color: 'transparent' }, overlayCSS: { allowTransparency: 'true', backgroundColor: 'transparent', opacity: 0.0, cursor: 'default'} });
}

//------  Open pop up Window
function wOpen(url, name, w, h) {
    w += 32;
    h += 96;
    var win = window.open(url,
  name,
  'width=' + w + ', height=' + h + ', ' +
  'location=0, menubar=0, ' +
  'status=0, toolbar=0, scrollbars=1 width=' + w + ' hight=' + h);
}

function truncateString(inputString, inputLength) {
    var truncatedStr = inputString;
    if (inputString.length > inputLength && inputLength > 3)
        truncatedStr = truncatedStr.substr(0, inputLength - 3) + "...";

    return escapeHTML(truncatedStr);
}
//------- 
function showShortStr(iName, iLength) {
    if (iName.length > iLength) {
        iName = iName.substring(0, iLength - 4);
        iName = ((iName.lastIndexOf(' ') == -1) ? (iName + "...") : (iName.substring(0, iName.lastIndexOf(' ')) + "..."))
    }
    return iName;
}

function buildProductTitle(brand, line, name) {
    resultName = "";
    if (brand == null)
        brand = "";
    if (line == null)
        line = "";
    if (name == null)
        name = "";

    if (brand != "") {
        // if the brand name is contained in the actual name of the
        // product, then we don't want to append it.
        // so first we check to see if the name is empty.
        // if it is empty then we don't care, just append the name
        if (name == "") {
            resultName += brand;
        }
        else {
            // We only want the full word of the brand to throw this guy off.
            // if the brand is GE, we don't want to throw away "hair gel".
            // so we only look for the full word "GE"

            // It could start with the "brand" with a space after it
            if (!(name.indexOf(brand + " ") == 0) &&
            // or the name has the brand with spaces before & after
                !(name.indexOf(" " + brand + " ") > -1) &&
            // or the name ends with the brand with a space before it.
                !name.endsWith(" " + brand) &&
            // and I guess the brand & the name could be the same.  If so
            // we should ignore it too.
                !(name == brand)) {
                resultName += brand;
            }
        }
    }
    if (line != "") {
        if (resultName.length != 0) {
            resultName += " ";
        }
        resultName += line;
    }
    if (name != "") {
        if (resultName.length != 0) {
            resultName += " ";
        }
        resultName += name;
    }
    return resultName;
}
//----------------- Value Amount ----------------
function valAmount(numValue) {
    if (numValue % 100 == 0) {
        numValue = (numValue / 100) + ".00";
    }
    else {
        if ((numValue % 100).toString().length < 2)
            numValue = Math.floor((numValue / 100)) + ".0" + (numValue % 100);
        else
            numValue = Math.floor((numValue / 100)) + "." + (numValue % 100);
    }
    return numValue;
}
//------ EMAIL ADDR VALIDATION -------------------
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

//------------------
function getStoreNameById(storeList, StoreID) {
    var storeName = "";
    $.each(storeList, function (i, item) {
        if (StoreID == item.ID) {
            storeName = item.Name;
            return;
        }
    });

    return storeName;
}


function escapeHTML(inputStr) {
    if (inputStr == null)
        return "";

    return inputStr.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
function unEscapeHTML(inputStr) {
    if (inputStr == null)
        return "";

    return inputStr.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
}

//Remove special characters before sending to PredictiveSearch
function removeSpecChars(inputStr) {
    return inputStr.replace(/</g, "").replace(/>/g, "").replace(/%/g, "").replace(/\//g, "").replace(/\?/g, "");
}

//-------------------------------------
function SortByUnis(x, y) {
    if (x != "" && y != "")
        return ((Number(x.Unis) == Number(y.Unis)) ? 0 : ((Number(x.Unis) > Number(y.Unis)) ? 1 : -1));
}
//-------------------------------------
function SortByTitle(x, y) {
    if (x != "" && y != "")
        return ((x.Title == y.Title) ? 0 : ((x.Title > y.Title) ? 1 : -1));
}
//-------------------------------------
function SortByAName(x, y) {
    if (x != "" && y != "")
        return ((x.AName == y.AName) ? 0 : ((x.AName > y.AName) ? 1 : -1));
}
//-------------------------------------
function SortBySequence(x, y) {
    if (x != "" && y != "")
        return ((x.Sequence == y.Sequence) ? 0 : ((x.Sequence > y.Sequence) ? 1 : -1));
}

function updateSyncID() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: WebServicesLocation + "CLIPBridgeWS.asmx/getLatestSyncPackageID",
        data: "{\"userID\":" + JSON.stringify(UserID) + "}",
        dataType: "json",
        success: function (data) {
            data = data.d;
            var syncID = eval(data);
            gl_syncID = data;
        }
    });
}

//--------ITEM DESCRIPTION----------
function itemDesc(objListItem) {
    if (objListItem.PPW == null)
        objListItem.PPW = 0;
    if (objListItem.PPQ == null)
        objListItem.PPQ = 0;
    var strHTML = "";
    var UseWeight = objListItem.UseWeight;
    var Weight = objListItem.Weight;
    var Quantity = objListItem.Quantity;
    var Price = (UseWeight ? objListItem.PPW : objListItem.PPQ);
    var Desc = escapeHTML(objListItem.Desc);
    var PackageInfo = "";
    var Note = escapeHTML(objListItem.Note);

    var arrItemAttrValues = objListItem.AttrValues; // Attributes as String
    if (arrItemAttrValues == "")
        arrItemAttrValues = [];
    else
        arrItemAttrValues = eval(objListItem.AttrValues);

    var AttrValuesInfo = "";

    // package info
    var objItemPackageInfo = objListItem.ItemPackageInfo;
    //if (objItemPackageInfo == null)
    //    objItemPackageInfo
    $.each(objItemPackageInfo, function (i, item) {
        if (item.Sel == "1") {
            PackageInfo = " " + item.Unis + " " + UnitOfMesure[item.UOM];
            PackageInfo += (item.Container == null ? "" : " " + item.Container);
            PackageInfo += (item.CUnis == null ? "" : " " + item.CUnis + " " + UnitOfMesure[item.CUOM]);
            PackageInfo += (item.CContainer == null ? "" : " " + item.CContainer);
            return;
        }
    });

    //Attrs
    if (arrItemAttrValues.length != 0) {
        var objItemAttrValues = arrItemAttrValues;
        var chrCommar = "";
        $.each(objItemAttrValues, function (i, AttrVarsArrs) {
            $.each(AttrVarsArrs, function (propertyName, AttrVars) {
                AttrValuesInfo += chrCommar + AttrVars; //alert(AttrVars);
                chrCommar = ", ";

            });
        });
    };

    if (UseWeight && Weight != "" && Weight > 0) { strHTML = Weight + " lbs" };
    if (!UseWeight && Quantity != "" && Quantity > 1) { strHTML = "Qty " + Quantity };

    Price = ((Price != 0) ? ("$" + valAmount(Price)) : "");
    if (UseWeight) { Price = ((Price != 0) ? (Price + "/lb") : ""); }

    var chrSepar1 = (strHTML.length > 0 && Price.length > 0 ? " @ " : "");
    strHTML = strHTML + chrSepar1 + Price;

    if (strHTML.length > 0) { strHTML = "<span class='descInfo'>" + strHTML + "</span>"; }

    var greyStrHTML = Desc;

    if (AttrValuesInfo != "") {
        if (greyStrHTML != "")
            greyStrHTML += ", ";
        greyStrHTML += AttrValuesInfo;
    };

    if (PackageInfo != "") {
        if (greyStrHTML != "")
            greyStrHTML += ", ";
        greyStrHTML += PackageInfo;
    };

    if (Note != "") {
        if (greyStrHTML != "")
            greyStrHTML += ", ";
        greyStrHTML += Note;
    };

    if (strHTML != "") {
        if (greyStrHTML != "")
            greyStrHTML = " - " + greyStrHTML;
    };

    strHTML += greyStrHTML;


    if (strHTML.indexOf("<span class='descInfo'>") == -1 && strHTML.length > 85)
        strHTML = showShortStr(strHTML, 85);

    if (strHTML.indexOf("<span class='descInfo'>") != -1 && strHTML.length > 120)
        strHTML = showShortStr(strHTML, 120);

    return strHTML;
}

//====== SubTitle =======
function getSubTitle(objListItem) {
    /*if item has description
        append description to subtitle
    if item has attributes
        for each attribute
            if attribute has selected value
                append selected attribute info to subtitle
    if item is not using weight and has selected package
        append selected package info to subtitle*/


    var strHTML = "";
    var Desc = escapeHTML(objListItem.Desc);
    var PackageInfo = "";

    var arrItemAttrValues = objListItem.AttrValues; // Attributes as String
    if (arrItemAttrValues == "")
        arrItemAttrValues = [];
    else
        arrItemAttrValues = eval(objListItem.AttrValues);

    var AttrValuesInfo = "";

    // package info
    var objItemPackageInfo = objListItem.ItemPackageInfo;

    $.each(objItemPackageInfo, function (i, item) {
        if (item.Sel == "1") {
            PackageInfo = " " + item.Unis + " " + UnitOfMesure[item.UOM];
            PackageInfo += (item.Container == null ? "" : " " + item.Container);
            PackageInfo += (item.CUnis == null ? "" : " " + item.CUnis + " " + UnitOfMesure[item.CUOM]);
            PackageInfo += (item.CContainer == null ? "" : " " + item.CContainer);
            return;
        }
    });

    //Attrs
    if (arrItemAttrValues.length != 0) {
        var objItemAttrValues = arrItemAttrValues;
        var chrCommar = "";
        $.each(objItemAttrValues, function (i, AttrVarsArrs) {
            $.each(AttrVarsArrs, function (propertyName, AttrVars) {
                AttrValuesInfo += chrCommar + AttrVars; //alert(AttrVars);
                chrCommar = ", ";

            });
        });
    };

    strHTML = strHTML;

    var subTtl = Desc;

    if (AttrValuesInfo != "") {
        if (subTtl != "")
            subTtl += ", ";
        subTtl += AttrValuesInfo;
    };

    if (PackageInfo != "") {
        if (subTtl != "")
            subTtl += ", ";
        subTtl += PackageInfo;
    };

    return subTtl;
}
