﻿// 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);
}

/// Warning: Getting a new session Id is an asynchronous funtion
wsi.GetNewSessionId = function()
{
    var aParameters = new wsi._Parameters();
    wsi._Soap.AddCall("GetNewSessionId", wsi.GetNewSessionReturn, aParameters);
}

wsi.GetNewSessionReturn = function(sessionId)
{
    /// Save session Id
    wsi._Cookie.SaveCrumb("SessionID", sessionId);
}

// 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();

    /// Get Product data off the page
    var MainProductTitle = document.getElementById("ShortTitle").innerHTML;
    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;

    var MainProductNoFreeShipping = false;
    if (document.getElementById("MainProductData").getAttribute("pd_NoFreeShipping") != null)
    {
        MainProductNoFreeShipping = document.getElementById("MainProductData").getAttribute("pd_NoFreeShipping");

    }

    var MainProductFlatRateShip = 0;
    if (document.getElementById("MainProductData").getAttribute("pd_FlatRateShipping") != null)
    {
        MainProductFlatRateShip = document.getElementById("MainProductData").getAttribute("pd_FlatRateShipping");

    }
    
    /// Build the product image
    if (MainProductImage.toLowerCase().indexOf(".com") > 0)
    {
        var Delimiter = MainProductImage.toLowerCase().indexOf(".com/");
        MainProductImage = MainProductImage.slice(Delimiter + 4);
    }

    /// Build the group id
    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" && AddOn.indexOf('REPLACEMENT') == -1)
            {
                var AddOnFields = AddOn.split("|");
                if (AddOnFields.length == 6)
                {/// If the data does not contain a sku, add a blank field
                    for (var isku = AddOnFields.length; isku > 1; isku--)
                    {
                        AddOnFields[isku] = AddOnFields[isku - 1];
                    }
                }

                AddOnFields[1] = "-"; /// replace the sku with a dash

                GroupID += "-" + AddOnFields[4] + ":" + AddOnFields[2]
            }

        }

    } while (ContinueLoop);

    ///<GroupId>|<SKU>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<Img>|<URL>
    //var MainProduct = GroupID+"|"+MainProductSku+"|"+MainProductID+"|"+MainProductTitle+"|"+MainProductQty+"|"+MainProductPrice+"|"+MainProductWeight+"|"+MainProductImage+"|"+document.location.href;
    ///<GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>|<CouponPrice>|<Coupon>

    var MainProduct = "";
    var ParentID = "";

    if (Checkout.Cart.Mode == "Server")
    {
        MainProduct = GroupID + "|" + MainProductSku + "|" + MainProductID + "|" + MainProductTitle + "|" + MainProductQty + "|" + MainProductPrice + "|" + MainProductWeight + "|" + MainProductImage + "|" + document.location.href + "|" + MainProductNoFreeShipping + "|" + MainProductFlatRateShip;
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        MainProduct = GroupID + "|0|" + MainProductID + "|" + MainProductTitle + "|" + MainProductQty + "|" + MainProductPrice + "|" + MainProductWeight + "|" + MainProductSku + "|" + MainProductImage + "|" + document.location.href;

        ParentID = MainProductSku;
    }

    var CartData = MainProduct;

    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" && AddOn.indexOf('REPLACEMENT') == -1)
            {
                var AddOnItems = AddOn.split("|");
                if (AddOnItems.length == 6)
                {/// If the data does not contain a sku, add a blank field
                    for (var isku = AddOnItems.length; isku > 1; isku--)
                    {
                        AddOnItems[isku] = AddOnItems[isku - 1];
                    }
                }

                AddOnItems[1] = "-"; /// replace the sku with a dash



                if (AddOnItems[4] != "1")
                {
                    AddOnItems[3] = "Qty " + AddOnItems[4] + " - " + AddOnItems[3];
                }

                /// We need one add on for each Main Products
                AddOnItems[4] = MainProductQty * parseInt(AddOnItems[4]);


                if (Checkout.Cart.Mode == "Server")
                {
                    AddOn = AddOnItems.join("|");

                    CartData += "|" + AddOn + "|-|-|-|-";
                }
                else if (Checkout.Cart.Mode == "Cookie")
                {
                    /// This is how it comes from the product page
                    /// <Type>|<SKU>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>                
                    /// This is the format we need
                    ///<GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>  

                    AddOnItems[7] = AddOnItems[1];
                    AddOnItems[9] = "-";
                    AddOnItems[8] = "-";
                    AddOnItems[0] = GroupID;
                    AddOnItems[1] = ParentID; /// Do this one after moving the Sku to position 7

                    AddOn = AddOnItems.join("|");

                    CartData += "||" + AddOn;
                }
            }
        }

    } while (ContinueLoop);
    //alert(CartData);
    //window.clipboardData.setData("Text", CartData);
    if (Checkout.Cart.Mode == "Server")
    {
        wsi.Cart.Save(CartData);
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        Checkout.CartProcessor.AddToCart(CartData)
        wsi.Cart.GetViewText();
    }
}

/// Server Based cart
wsi.Cart.Save = function(cartData)
{
    SessionID = (wsi._Cookie.GetCrumb("SessionID") == null ? "" : wsi._Cookie.GetCrumb("SessionID"));

    //window.clipboardData.setData("Text", cartData);
    //alert(cartData)
    var aParameters = new wsi._Parameters();
    aParameters.Add("sessionID", SessionID);
    aParameters.Add("cartData", cartData);

    wsi._Soap.AddCall("SaveToCart", wsi.Cart.SaveReturn, aParameters);

    /// Hide the Checkout button.
    /// Work-around for slow connections.
    /// Navigating away from the page before the item
    /// is saved to cart will result in data loss.
    var AnchorCollection = document.getElementsByTagName("A");

    for (var i = 0; i < AnchorCollection.length; i++)
    {
        /// Get the anchor
        var Anchor = AnchorCollection[i];

        /// The anchor may not have 
        if (Anchor.href.indexOf("checkout.htm") > -1)
        {
            Anchor.style.visibility = "hidden";
        }
    }
}

/// Server Based cart
wsi.Cart.SaveReturn = function(returnValue)
{

    ParamArray = returnValue.split("|");

    wsi._Cookie.SaveCrumb("SessionID", ParamArray[0]);
    ParamList = ParamArray[1] + "|" + ParamArray[2];

    wsi.Cart.SetViewText(ParamList);

    /// Show the Checkout button.
    var AnchorCollection = document.getElementsByTagName("A");

    for (var i = 0; i < AnchorCollection.length; i++)
    {
        /// Get the anchor
        var Anchor = AnchorCollection[i];

        /// The anchor may not have 
        if (Anchor.href.indexOf("checkout.htm") > -1)
        {
            Anchor.style.visibility = "inherit";
        }
    }

    //alert("Cart Saved: " + sessionID);
}

wsi.Cart.GetViewText = function()
{
    if (Checkout.Cart.Mode == "Server")
    {
        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
        {
        }
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        wsi.Cart.SetViewText(Checkout.CartProcessor.CartQty()+"|"+Checkout.CartProcessor.CartTotal());
   }
}

wsi.Cart.SetViewText = function(paramList) {

    if (paramList.toLowerCase().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;
            }
        }
        //alert(document.getElementById("panel1_c").style.visibility);

    }
    else
    {
        //alert(paramList);
    }
}


///////// 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 != null)
            {
                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
                    }
                }
            }
            else
            {
                l_return = "Error: unable to retrieving data from the server."
            }
        }
    }
  
	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);
}