﻿// WSI.js - Web Service Interface
// version 0.00.0001
//
////////////////////////////////////////////////////////////
//
// This JS file contains two main sections.
// 1) Public: containing a set of provider objects
//            intended for external use as an
//            interface to all availble Web Services.
//
// 2) Private: objects designed for internal use by
//             public objects. These objects are not meant
//             to be accessed directly by external objects.
//
////////////////////////////////////////////////////////////

//////// Public ////////////////////////////////////////////

wsi = new Object();


wsi.GetIP = function(returningFunction)
{
    var aParameters = new wsi._Parameters();
    wsi._Soap.AddCall("GetIpAddress", returningFunction, aParameters);
}


// Cart Object
wsi.Transaction = new Object();
wsi.Cart = new Object();

wsi.Transaction.ParseProductPage = function()
{
    wsi.Cart.ParseProductPage();
}

wsi.Cart.ValidateQty = function()
{
    var MainProductQty = document.getElementById("MainProductQty").value;
    if (MainProductQty.match(/[^0-9]/))
    {
        /// Strip all non numeric characters
        document.getElementById("MainProductQty").value = MainProductQty.replace(/[^0-9]/g, "");
    }
    
    /// Don't allow 0 Qty
    if (MainProductQty == "0")
    {
        document.getElementById("MainProductQty").value = "1";
    }
}

wsi.Cart.ParseProductPage = function()
{

    wsi.Cart.ValidateQty();
    var MainProductTitle = document.getElementById("ShortTitle").innerHTML;
    //MainProductTitle = MainProductTitle.replace(/\'/g, "");
    var MainProductSku = document.getElementById("PartNumber").innerHTML.substring(13);// remove "Part Number: "
    var MainProductID = document.getElementById("MainProductData").getAttribute("pd_nsid");
    var MainProductPrice = document.getElementById("MainProductData").getAttribute("pd_price");
    var MainProductWeight = document.getElementById("MainProductData").getAttribute("pd_weight");
    var MainProductQty = document.getElementById("MainProductQty").value;
    var MainProductImage = document.getElementById("ProductImage").src;
    
    
    if (MainProductImage.toLowerCase().indexOf(".com") > 0)
    {
        var Delimiter = MainProductImage.toLowerCase().indexOf(".com/");
        MainProductImage = MainProductImage.slice(Delimiter+4);
    }
    
    var GroupID = MainProductID;
    var i=0;
    var ContinueLoop = true;
    do
    {
        ++i;
        var AddOn = document.getElementById("AddOn"+i);
        if (AddOn == null)
        {
            ContinueLoop = false;
        }
        else
        {
            AddOn = document.getElementById("AddOn"+i).value;

            if (AddOn.length > 0 && AddOn.toLowerCase() != "none")
            {
                var AddOnFields = AddOn.split("|");
                
                //var Delimiter = AddOn.indexOf('|');
                //var Delimiter2 = AddOn.indexOf('|', Delimiter+1);
                //GroupID += "-" + AddOn.substring(Delimiter+1, Delimiter2) 
                GroupID += "-" + AddOnFields[3] + ":" + AddOnFields[1] 
            }
            
        }

    }while(ContinueLoop);
    
    //<GroupId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>
    var MainProduct = GroupID+"|"+MainProductID+"|"+MainProductTitle+"|"+MainProductQty+"|"+MainProductPrice+"|"+MainProductWeight+"|"+MainProductSku+"|"+MainProductImage+"|"+document.location.href;
    
    var CartData = MainProduct;
//alert(CartData);
    i=0;
    ContinueLoop = true;
    do
    {
        ++i;
        var AddOn = document.getElementById("AddOn"+i);
        if (AddOn == null)
        {
            ContinueLoop = false;
        }
        else
        {
            AddOn = document.getElementById("AddOn"+i).value;
            if (AddOn.length > 0 && AddOn.toLowerCase() != "none")
            {
                var AddOnItems = AddOn.split("|");
                
                if (AddOnItems[3] != "1")
                {
                    AddOnItems[2] = "Qty " + AddOnItems[3] + " - " + AddOnItems[2];
                    AddOn = AddOnItems.join("|");
                }
                
                CartData += "|"+AddOn+"|-|-|-";
            }
        }

    }while(ContinueLoop);

    wsi.Cart.Save(CartData);
}

wsi.Cart.Save = function(cartData)
{
    SessionID = (wsi._Cookie.GetCrumb("SessionID") == null ? "" : wsi._Cookie.GetCrumb("SessionID"));

    var aParameters = new wsi._Parameters();
    aParameters.Add("sessionID",SessionID);
    aParameters.Add("cartData",cartData);

    wsi._Soap.AddCall("SaveToCart", wsi.Cart.SaveReturn, aParameters);
}

wsi.Cart.SaveReturn = function(returnValue)
{
    ParamArray = returnValue.split("|");
    
    wsi._Cookie.SaveCrumb("SessionID", ParamArray[0]);
    ParamList = ParamArray[1]+"|"+ParamArray[2];

    wsi.Cart.SetViewText(ParamList);
    
    //alert("Cart Saved: " + sessionID);
}

wsi.Cart.GetViewText = function()
{

    SessionID = wsi._Cookie.GetCrumb("SessionID");

    if (SessionID != null)
    {
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionID",SessionID);

        wsi._Soap.AddCall("GetCartPriceQty", wsi.Cart.SetViewText, aParameters);
    }
    else
    {
    }
}

wsi.Cart.SetViewText = function(paramList)
{

    if (paramList.indexOf("error") == -1)
    {
        wsi._Cookie.SaveCrumb("CartView", paramList);
        
        if(document.getElementById("CartItemCount") != null)
        {
            ParamArray = paramList.split("|");

            var CartItemCount = ParamArray[0];
            var CartTotal = ParamArray[1];
            if (CartItemCount != "undefined")
            {
                
                document.getElementById("CartItemCount").innerHTML = CartItemCount;
            }
            
            if (CartTotal != "undefined")
            {
                document.getElementById("CartTotal").innerHTML = CartTotal;
            }
        }
    }
}


///////// End Public ///////////////////////////////////////



///////// Private //////////////////////////////////////////

wsi._Soap = new Object(); // object used to send and receive ajax soap calls

wsi._Soap.Queue = new Array(); // contains all calls

wsi._Soap.AddCall = function(callMethod, callBack, callParameters) // add a call to the queue
{
    var oCallObject = new Object();
    oCallObject.CallMethod = callMethod;
    oCallObject.CallBack = callBack;
    oCallObject.CallParameters = callParameters;
    
    wsi._Soap.Queue[wsi._Soap.Queue.length] = oCallObject;
    
    wsi._Soap.Trigger();
}

wsi._Soap.Status = "idle"; // current processing state
wsi._Soap.Pointer = -1; // current queue position

wsi._Soap.Trigger = function()
{
    if (wsi._Soap.Status == "idle") // otherwise it is already processing
    {
        wsi._Soap.NextCall();
    }
}

wsi._Soap.NextCall = function()
{
    if (wsi._Soap.Pointer == wsi._Soap.Queue.length-1) // all calls have been processed
    {
        wsi._Soap.Status = "idle";
    }
    else // send the next call
    {
        wsi._Soap.Pointer++;
        wsi._Soap.Call();
    }
}
wsi._Soap.Call = function() // send a soap call
{
    wsi._Soap.Status = "processing"; // set status as in process
    
    var oCall = wsi._Soap.Queue[wsi._Soap.Pointer]; // get the next call off the queue
    
    var l_cLocation = document.location.protocol + "//" + document.location.host + "/";// + "safemart.com/";
	var l_cPath = l_cLocation;

    // open the xmlhttp object
	wsi._Soap.xmlhttp.open("POST", l_cPath + "WebService.asmx",true);
	wsi._Soap.xmlhttp.onreadystatechange=wsi._Soap.Response;
		
	wsi._Soap.xmlhttp.setRequestHeader("Man", "POST "+ l_cPath +"WebService.asmx HTTP/1.1");
	wsi._Soap.xmlhttp.setRequestHeader("MessageType", "CALL");
	wsi._Soap.xmlhttp.setRequestHeader("Content-Type", "text/xml");
	wsi._Soap.xmlhttp.setRequestHeader('Cache-Control', "max-age=1");
	wsi._Soap.xmlhttp.setRequestHeader('Pragma', "no-cache");
	
	var sCallParameters = "";
	//unpack parameters
	for (var i=0; i<oCall.CallParameters.Items.length; i++)
	{
	    var oParamName = oCall.CallParameters.Items[i][0];
	    var oParamValue = oCall.CallParameters.Items[i][1];
	    sCallParameters += "<"+ oParamName +">" + oParamValue + "</"+ oParamName + ">";
	}
//if (oCall.CallMethod == "PlaceOrder") alert(sCallParameters);
	wsi._Soap.xmlhttp.send(''+
			'<?xml version="1.0" encoding="utf-8"?>'+
			'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
				'<soap:Body>'+
					'<'+oCall.CallMethod+' xmlns="safemart.com">'+
						sCallParameters+
					'</'+oCall.CallMethod+'>'+
				'</soap:Body>'+
			'</soap:Envelope>');


}

wsi._Soap.Response =function() // callback responses handler
{

    var l_return = null;
    var oCall = null;


    if (wsi._Soap.xmlhttp.readyState==4)
    {// 4 = "loaded"
    
        oCall = wsi._Soap.Queue[wsi._Soap.Pointer];
        
        if (wsi._Soap.xmlhttp.status==200)
        {// 200 = OK
            if (wsi._Soap.xmlhttp.responseXML.getElementsByTagName(oCall.CallMethod+"Result")[0].firstChild == null)
            {
                l_return = ""
            }
            else
            {                
                l_return = wsi._Soap.xmlhttp.responseXML.getElementsByTagName(oCall.CallMethod+"Result")[0].firstChild.nodeValue;
            }
        }
        else
        {
            l_return = "error: ";
            if (wsi._Soap.xmlhttp.responseXML.getElementsByTagName("faultstring")[0] != null)
            {
                if (wsi._Soap.xmlhttp.responseXML.getElementsByTagName("faultstring")[0].firstChild != null)
                {
                    l_return += wsi._Soap.xmlhttp.responseXML.getElementsByTagName("faultstring")[0].firstChild.nodeValue
                }
            }
            
        }
    }
  
	if (l_return != null)
	{
	    wsi._Soap.close;
	    wsi._Soap.NextCall();
	    
	    // Send the return value back to the callback function
	    oCall.CallBack(l_return);
    }
    
}

if(window.XMLHttpRequest) //first look for native support
{
     wsi._Soap.xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
    // For IE version < IE7 try the various version of the MSXML ActiveX Object
    try
    {
        wsi._Soap.xmlhttp = new ActiveXObject("MSXML3.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            wsi._Soap.xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(e)
        {
            try
            {
                wsi._Soap.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e)
            {
                try
                {
                    wsi._Soap.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (E)
                {
                    wsi._Soap.xmlhttp = false;
                }
            }
         }
     }
     
}
else
{
    wsi._Soap.xmlhttp = false;
}


wsi._Parameters = function() // constructor for creating a new parameter object
{
    this.Items = new Array();
   
    this.Add = function(name, value)
    {
        var itemLen = this.Items.length;
        this.Items[itemLen] = new Array();
        this.Items[itemLen][0] = name;
        this.Items[itemLen][1] = escape(value);
    }    

}

wsi._Cookie = new Object();
wsi._Cookie.SaveCrumb = function(crumb, crumbValue){

	var l_dToday = new Date();
	var l_dThisYear = l_dToday.getFullYear()
	var l_dExpireDate = new Date(l_dThisYear + 10, 11, 31);
	if (crumbValue != '') document.cookie = crumb + '=' + crumbValue + ';expires=' + l_dExpireDate.toGMTString() + ';path=/; domain=.safemart.com';

}

wsi._Cookie.GetCrumb = function(crumb)
{
    var l_aCookie = document.cookie.split('; ');

    for (i = 0; i<l_aCookie.length; i++)
    { // look for the crumb
	    l_aCrumb = l_aCookie[i].split('=');
	    if (l_aCrumb[0] == crumb)
	    { // found the crumb, return the value
		    if(l_aCrumb.length > 1 && l_aCrumb[1].toLowerCase().indexOf("error") == -1)
		    {
		        return l_aCrumb[1]
		    }
		    else
		    {
		        return null;
		    }
	    }
	    else
	    { 
	        // no cookie, do nothing
	    }
    }
    return null //no crumb return null
}
///////// End Private /////////////////////////////////////////


///////// for Testing /////////////////////////////////////////

wsi._ReturnTest = function(returnMessage)
{
    alert("Return Message: "+ returnMessage);
}