﻿// JScript File
//jquery variables
var varType;
var varUrl;
var varData;
var varContentType;
var varDataType;
var varProcessData;  

String.prototype.trimEnd = function (c) {
    if (c)
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function (c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}
String.prototype.escapeRegExp = function () {
    return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};


getUrlEncodedKey = function (key, query) {
    if (!query)
        query = window.location.search;
    var re = new RegExp("[?|&]" + key + "=(.*?)&");
    var matches = re.exec(query + "&");
    if (!matches || matches.length < 2)
        return "";
    return decodeURIComponent(matches[1].replace("+", " "));
}
setUrlEncodedKey = function (key, value, query) {

    query = query || window.location.search;
    var q = query + "&";
    var re = new RegExp("[?|&]" + key + "=.*?&");


   /* if (!re.test(q)) {
        alert("1");
        q += key + "=" + encodeURI(value);
    }
    else {*/
     
       // q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
        q = q.replace(re, "&" + key + "=" + value + "&");
    //}
    //q = q.trimStart("&").trimEnd("&");
   
    return q[0] == "?" ? q : q = "?" + q;
}



function del_cookie(name) {
    document.cookie = name +
'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

}
function logout() {

    document.location = "/clearcookie.aspx?y=y";
}

function insertParam(key, value) {
    key = escape(key);
    value = escape(value);
    var kvp = document.location.search.substr(1).split('&');
    if (kvp == "") {
        document.location.search = key + "=" + value;
    }
    else {

        var param = new Array();
        param[0] = key + "," + value;
        param[1] = "pageno" + "," + 1;
        var cnt = 0
        while (cnt <= param.length - 1) {
            var spair = param[cnt].toString().split(",");
            key = spair[0];
            value = spair[1];
        
        var i = kvp.length;
        var x;
        while (i--) {
            x = kvp[i].split('=');
           
            if (x[0] == key) { 
                x[1] = value;
                kvp[i] = x.join('=');
                break;
            }
        }

        if (i < 0) {
           // alert(key + " " + value);
            kvp[kvp.length] = [key, value].join('=');
        } //this will reload the page, it's likely better to store this until finished
        cnt++;
    }
      // alert(kvp);

        document.location.search = kvp.join('&');
    }
}


function updateURL(ctrl, qry) {
   
    insertParam(qry, ctrl.value);    
}
function updateURL2(ctrlName, qry) {

    var ctrl = document.getElementById(ctrlName);
    
    if (ctrl.value == "Enter Brand Name")
        ctrl.value = "";
    else if (ctrl.value == "Enter Supplier Name")
        ctrl.value = "";
    insertParam(qry, ctrl.value);
    return false;
}

function NavigateURL(ctrl)
{    
    var ctrlurl = document.getElementById(ctrl)       
    window.open(ctrlurl.options[ctrlurl.selectedIndex].value,"_top","");
    
}
function ValidateForgotPassEmail(email1)
{
var emailctrl = document.getElementById(email1)
var email=isWhitespace(emailctrl);  
if (email.length == 0)
		{
			emailctrl.focus();
			alert("Please fill in your Email");			
			return false;			
		}
	else if(checkEmail(email)==false)
		{
			emailctrl.focus();
			alert("Please Enter Valid Email");
			return false;
		}   
return true;

}

function ServiceFailed(result) {
   // alert('Service call failed: ' + result.status + '' + result.statusText);
    varType = null; varUrl = null; varData = null; varContentType = null; varDataType = null; varProcessData = null;
}

function ServiceSucceeded(result, dv, ctrl) {//When service call is sucessful
    var dvError = document.getElementById(dv);
    var txt = document.getElementById(ctrl);

    if (result.toString() == "true") {        
        dvError.innerHTML = "Your email address is already in use";
        dvError.className = "FieldErrorMessage";
        txt.className = "PublicTextRed";
        txt.title = "Email address is already taken. Please enter different email address";
    }
    else {
        dvError.innerHTML = "";
        dvError.className = "";
        txt.className = "PublicText";
        txt.title = "Your email address is available";
    }
    
    //alert(dv);
}

function CallService(dv,ctrl) {
    $.ajax({

        type: varType, //GET or POST or PUT or DELETE verb
        url: varUrl, // Location of the service
        data: varData, //Data sent to server
        contentType: varContentType, // content type sent to server
        dataType: varDataType, //Expected data format from server
        processdata: varProcessData, //True or False
        success: function (msg) {//On Successfull service call
            ServiceSucceeded(msg, dv, ctrl);
        },
        error: ServiceFailed// When Service call fails
    });
}

//validate supplier email address
function validateSupplieremail(dv,url,ctrl) {
    var email = isWhitespace(document.getElementById(ctrl));
    if (email.length == 0) {
        return;
    }
         
    varType = "GET";    
    varUrl = url + email + "?callback=?"; ;
    varContentType = "application/json; charset=utf-8";
    varDataType = "json";
    varProcessData = false;
//alert(varUrl);
    CallService(dv, ctrl);
}
//validate supplier sku
function validateSupplierSKU(dv, url, ctrl) {
    var sku = isWhitespace(document.getElementById(ctrl));
    if (sku.length == 0) {
        return;
    }

    varType = "GET";
    varUrl = url + sku + "?callback=?"; ;
    varContentType = "application/json; charset=utf-8";
    varDataType = "json";
    varProcessData = false;
    CallService(dv);
}


function ValidateSupplierRegistration(company, firstname, lastname, midinit, emailaddress) {

    
    
    var emailctrl = document.getElementById(emailaddress)
    var firstnamectrl = document.getElementById(firstname)
    var companyctrl = document.getElementById(company)
    var lastnamectrl = document.getElementById(lastname)
    var midinitctrl = document.getElementById(midinit)

    var email = isWhitespace(emailctrl);
    var First = isWhitespace(firstnamectrl);
    var Company = isWhitespace(companyctrl);
    var Last = isWhitespace(lastnamectrl);
    var midInit = isWhitespace(midinitctrl);

    if (Company.length == 0) {
        companyctrl.focus();
        alert("Please fill in your Company Name");
        return false;
    }
    if (First.length == 0) {
        firstnamectrl.focus();
        alert("Please fill in your First Name");
        return false;
    }
    if (Last.length == 0) {
        lastnamectrl.focus();
        alert("Please fill in your Last Name");
        return false;
    }
    


    if (email.length == 0) {
        emailctrl.focus();
        alert("Please fill in your Email Address");
        return false;
    }
    else if (checkEmail(email) == false) {
        emailctrl.focus();
        alert("Please Enter Valid Email Address");
        return false;
    }

    if (document.getElementById("chk").checked == false) {
        alert("Please check mark your agreeement to our supplier terms of use");
        return false;
    }
    
    return true;

}
function ValidateSellWhole(name,company,phone,email1,desc)
{
//txtEmail

var emailctrl = document.getElementById(email1)
var namectrl = document.getElementById(name)
var companyctrl = document.getElementById(company)
var phonectrl = document.getElementById(phone)
var descctrl = document.getElementById(desc)

    var email=isWhitespace(emailctrl);      
     name=isWhitespace(namectrl);      
     company=isWhitespace(companyctrl);      
     phone=isWhitespace(phonectrl);
     desc = isWhitespace(descctrl);       
    
    if (name.length == 0)
		{
			namectrl.focus();
			alert("Please fill in your Name");			
			return false;			
		}    
	if (company.length == 0)
		{
			companyctrl.focus();
			alert("Please fill in your Company");			
			return false;			
		}
	if (phone.length == 0)
		{
			phonectrl.focus();
			alert("Please fill in your Phone");			
			return false;			
		}
	
    if (email.length == 0)
		{
			emailctrl.focus();
			alert("Please fill in your Email");			
			return false;			
		}
	else if(checkEmail(email)==false)
		{
			emailctrl.focus();
			alert("Please Enter Valid Email");
			return false;
		}   
		
		if (desc.length == 0)
		{
			descctrl.focus();
			alert("Please fill in your Description of Products");			
			return false;			
		}    	    	    	
	return true;
}

 function CheckRegisterCustomer(ctrl)
 { 
 
  var email=isWhitespace(ctrl);  
    if (email.length == 0)
		{
			ctrl.focus();
			alert("Please fill in your Email");
			ctrl.focus();
			return false;			
		}
	else if(checkEmail(email)==false)
		{
			ctrl.focus();
			alert("Please Enter Valid Email");
			return false;
		}    
 
    PageMethods.CusotmerRegistered(email,OnSucceeded, OnFailed);
    
 }
 
 function SearchInventory(queryfield)
 {
 
    var query = isWhitespace(document.getElementById(queryfield));
    if (query.length == 0)
    {
        document.getElementById(queryfield).focus();
        alert("Please enter inventory name or item number to continue");
        return false;
    }
 
    window.open("searchresult.aspx?query=" +query,"_top","");
    return false;
 }
 function RegisterNewCustomer(login,pass,confirmpass,term,sub)
 {
 var email=isWhitespace(document.getElementById(login));
    if (email.length == 0)
		{
			document.getElementById(login).focus();
			alert("Please fill in your Email");
			return false;
			
		}
	else if(checkEmail(email)==false)
		{
			document.getElementById(login).focus();
			alert("Please Enter Valid Email");
			return false;
		}
     var password1=isWhitespace(document.getElementById(pass));
     if (password1.length == 0)
        {
            document.getElementById(pass).focus();
            alert("Please enter password to continue");
            return false;
        }
        
     var password2=isWhitespace(document.getElementById(confirmpass));
     if (password2.length == 0)
        {
            document.getElementById(confirmpass).focus();
            alert("Please re-enter your password to continue");
            return false;
        }
        if (password1 != password2)
        {
            alert("Your password does not match with confirmed password. Please re-enter same passwords");
            return false;
        }
      if (term !=null)
      { 
          if (document.getElementById(term).checked == false)
          {
                alert("Please check mark your agreeement to our terms of use");
                return false;
          }
      }
//      if (document.getElementById(sub).checked == false)
//      {
//            alert("In order to continue you need to select term of use");
//            return false;
//      }      
    
 }
 
 


function ValidateLogin(login,pass)
{
    var email=isWhitespace(document.getElementById(login));
    if (email.length == 0)
		{
			document.getElementById(login).focus();
			alert("Please fill in your Email");
			return false;
			
		}
	else if(checkEmail(email)==false)
		{
			document.getElementById(login).focus();
			alert("Please Enter Valid Email");
			return false;
		}
     var password1=isWhitespace(document.getElementById(pass));
     if (password1.length == 0)
        {
            document.getElementById(pass).focus();
            alert("Please enter password to continue");
            return false;
        }
    return true;
}

    
function SubscribeEmail(ctrl)
{
    
    var email=isWhitespace(document.getElementById(ctrl));
    if (email.length == 0)
		{
			document.getElementById(ctrl).focus();
			alert("Please fill in your Email");
			return false;
			
		}
	else if(checkEmail(email)==false)
		{
			document.getElementById(ctrl).focus();
			alert("Please Enter Valid Email");
			return false;
		}
    
    return true;
    
   
    document.getElementById("txtemail").value = "";
    
}
function AddToCart(ProductID,Qty)
{
    var qty = document.getElementById(Qty).value;
    //alert(qty);
    PageMethods.AddItemToCart(ProductID,qty, OnSucceeded, OnFailed);                   
    
}

function ReadReviews(key) 
{
    PageMethods.SetSessionValue(key, value, 
        OnSucceeded, OnFailed);
}

function GetCartItems()
{        
    PageMethods.GetCartItemCount(OnSucceeded, OnFailed);                       
}

function SubmitPrice() {

PageMethods.SubmitPriceApprovalRequest(OnSucceeded,OnFailed);
return false;
}



// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "SubmitPriceApprovalRequest")
    {
        alert(result);
        window.navigate(document.getElementById("URL").value);
        
    }
    
    if (methodName == "AddSupplierReview")
    {
        alert("Thank you for reviewing this supplier");
        var SupplierID = $get("hSupplierID").value;
        window.open("Suppliers.aspx?sp=" + SupplierID + "#reviews","_top","","");        
    }

    if (methodName == "AddProductReview")
    {
        alert("Thank you for reviewing this product");
        var ProductID = $get("hProductID").value;
        window.open("Webproductdetail.aspx?ID=" + ProductID,"_top","","");
        //displayElement.innerHTML = "Current session state value: " + 
          //  result;
    }
    if (methodName == "SubscribeEmail")
    {
        if (result == null)
            alert("You have been added to our email list. Thank you.");
        else
            alert(result);
              
    }
    if (methodName == "CusotmerRegistered")
    {
        if (result !=null)
        alert(result);
    }
    if (methodName == "AddReview")
    {
        var SupplierID = $get("hSupplierID").value;
        window.open("SupplierReviews.aspx?ID=" + SupplierID,"_top","","");
       
    }
    
    if (methodName == "AddItemToCart" || methodName == "GetCartItemCount")
    {  
    
        if (result[0])
        {
            $get("dvCartItems").innerHTML = "<p><strong>" + result[2] + " Items in Cart&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href='ViewCart.aspx'>View Cart</a></strong></p>";
            $get("dvCheckOutSaving").innerHTML = "<p>Check out now, you could make<span class='make'> $"+result[3]+" *</span></p>";
        }
        else
            alert(result[1]);
               
    }
    
    if (methodName == "FetchResaleCert" || methodName=="AddResaleCert" || methodName=="DeleteCert")
    {  
       
        var Certs = $get("dvResale");
        Certs.innerHTML = result;             
    }   
    if (methodName == "DeleteCert")
        alert("Resale Certificate has been successfully removed");
     
    
    
}

// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) 
{
    if(error !== null) 
    {
        alert(error.get_message());
    
    }
}

/////////////////////////////Buyer Registration///////////////////////////////


