/******************************************
*                                         *
*             Prototypes                  *
*                                         *
*                                         *
*******************************************/

Array.prototype.find = function(search)
{
    var i = 0;
    while (this[i] != search && i < this.length)
    {
        ++i;
    }

    if (i == this.length)
    {
        i = -1;
    }
    return (i);
}

if (typeof (Array.prototype.findAt) == "undefined")
{
    Array.prototype.findAt = function(needle, p_nStartLoc, p_cMatch, p_cExclusions)
    {
        if (typeof (p_cMatch) == 'undefined') p_cMatch = 'exact';
        if (typeof (p_cExclusions) == 'undefined') p_cExclusions = '';

        if (p_cExclusions.length > 0)
        {
            //	p_cExclusions = a string containing chars to remove from the search_string
            //		before performing the compare. For example, to remove all instances
            //		of "a', "b", and "c" p_cExclusions would equal "abc".

            var regExp = eval('/[' + p_cExclusions + ']/g');
        }
        else
        {
            var regExp = null;
        }

        var i = p_nStartLoc;

        if (p_cMatch == 'exact')
        {
            for (i = p_nStartLoc; i < this.length; i++)
            {
                var l_cSearch = this[i];

                if (regExp != null)
                {
                    //alert(l_cSearch);
                    l_cSearch = l_cSearch.replace(regExp, "");
                    //alert(l_cSearch);
                }

                if (l_cSearch != null)
                {
                    if (l_cSearch == needle) break;
                }
            }
        }
        else if (p_cMatch == 'contains')
        {
            for (i = 0; i < this.length; i++)
            {
                if (this[i] != null)
                {
                    var v_numtostr = this[i].toString()
                    if (v_numtostr.indexOf(needle) != -1) break;
                }
            }
        }
        else if (p_cMatch == 'containswhole')
        {
            for (i = 0; i < this.length; i++)
            {
                if (this[i] != null)
                {
                    var v_numtostr = this[i].toString()
                    if (parseInt(needle) == parseInt(this[i])) break;
                }
            }
        }

        else if (p_cMatch == 'containsround')
        {
            for (i = 0; i < this.length; i++)
            {
                if (this[i] != null)
                {
                    var v_numtostr = this[i].toString()
                    if (Math.round(parseFloat(needle)) == Math.round(parseFloat(this[i]))) break;
                }
            }
        }

        if (i == this.length)
        {
            i = -1;
        }
        return (i);
    }
}

/******************************************
*                                         *
*            End Prototypes               *
*                                         *
*                                         *
*******************************************/

/// public variables
ProductSku = null;

// Root level namespace for this js file
Safemart = new Object();
SWH = new Object();


Safemart.WriteTrace = function(msg)
{
    if (document.getElementById("trace") != null)
    {
        document.getElementById("trace").innerHTML += "<br><br> " + msg;
    }
}

Safemart.GetSession = function()
{
    return (wsi._Cookie.GetCrumb("SessionID") == null || wsi._Cookie.GetCrumb("SessionID") == "NaN" ? "" : wsi._Cookie.GetCrumb("SessionID"));
}

function onKey(e)
{
/*
    switch(e.keyCode){
        case 107: /// +
            var gac = new gaCookies();
            var CampaignName = gac.getCampaignName();
            var SessionCounter = gac.getSessionCounter();
            var CampaignSource = gac.getCampaignSource();
            var CampaignMedium = gac.getCampaignMedium();
            var CampaignTerm = gac.getCampaignTerm();
            var CampaignContent = gac.getCampaignContent();
            alert("CampaignName: " + CampaignName + "\r\nSessionCounter: " + SessionCounter + "\r\nCampaignSource: " + CampaignSource + "\r\nCampaignMedium: " + CampaignMedium + "\r\nCampaignTerm: " + CampaignTerm + "\r\nCampaignContent: " + CampaignContent)
            break;
    }
*/
}

Safemart.Init = function()
{
    wsi.GetNewSessionId();
    /*
    var QueryString = new Safemart.QueryString();
    var CampaignId = QueryString.Find("campaign");
    if (CampaignId != null)
    {
    wsi._Cookie.CampaignId(CampaignId);
    }
    */
    if (gaCookies != null)
    {
        if (document.body.addEventListener)
        {
            document.addEventListener("keyup", onKey, false);
        }
    }

    if (document.getElementById("CustomerCenterPage") != null)
    {
        /// Initialize the CustomerCenter
        //CustomerCenter = new Safemart.CustomerCenter();
        CustomerCenter.Login();
    }

    if (document.getElementById("MainProductData") != null)
    {
        Safemart.ProductPage = new Safemart.ProductPageHandler();
        ProductSku = Safemart.ProductPage.GetSku();
        Safemart.EnableCheckAvailability();
        Safemart.ProductPage.SetOverlayText();

    }

    /*
    Safemart.Analytics.PageVisit(document.location.href, document.referrer);

    if (document.body.addEventListener)
    {
    document.addEventListener("mousedown", function(e) { return Safemart.Analytics.Click(e); }, false);
    window.addEventListener("unload", function() { return Safemart.Analytics.PageExit(); }, false);
    }
    else if (document.body.attachEvent)
    {
    document.body.attachEvent("onmousedown", function() { return Safemart.Analytics.Click(); });
    window.attachEvent("onunload", function() { return Safemart.Analytics.PageExit(); });
    }
    else
    {
    document.body.onclick = Safemart.Analytics.Click;
    window.onunload = Safemart.Analytics.PageExit;
    }
    */
}

Safemart.Analytics = new Object();
Safemart.Analytics.PageVisit = function(url, referrer)
{
    SessionID = Safemart.GetSession();
    var aParameters = new wsi._Parameters();
    aParameters.Add("sessionId", SessionID);
    aParameters.Add("url", url);
    aParameters.Add("referrer", referrer);
    wsi._Soap.AddCall("PageVisit", Safemart.Analytics.PageVisitReturn, aParameters);
}

Safemart.Analytics.PageVistId = 0;

Safemart.Analytics.PageVisitReturn = function(returnValue)
{

    var ParamArray = returnValue.split("|");

    //alert(returnValue);
    //window.status = "Valid Session Id: " + !isNaN(parseInt(ParamArray[0]));

    /// Session Id should be a number. Otherwise, it's likely an error.
    /// A session Id is now created on page load.
    //if (!isNaN(parseInt(ParamArray[0])))
    //{
    //    wsi._Cookie.SaveCrumb("SessionID", ParamArray[0]);
    //}

    if (!isNaN(parseInt(ParamArray[1])))
    {
        Safemart.Analytics.PageVistId = ParamArray[1];
    }
}

Safemart.Analytics.PageExit = function()
{
    //alert("PageExit");
    if (Safemart.Analytics.PageVistId > 0)
    {
        var aParameters = new wsi._Parameters();
        aParameters.Add("pageVisitId", Safemart.Analytics.PageVistId);
        wsi._Soap.AddCall("PageExit", "", aParameters);
    }
}

Safemart.Analytics.Click = function(e)
{
    if (Safemart.Analytics.PageVistId > 0)
    {
        e = e || window.event;
        var clicktarget = e.target || e.srcElement;

        var Target = Safemart.Analytics.FindTarget(clicktarget);

        if (Target.EventType != null && (Target.ObjectId != null || Target.Href != null))
        {
            //window.status = "You clicked on \"" + Target.ObjectId + "\" a " + Target.ObjectName + " tag raising the " + Target.EventType + " event " + Target.Href;

            var aParameters = new wsi._Parameters();
            aParameters.Add("pageVisitId", Safemart.Analytics.PageVistId);
            aParameters.Add("eventType", Target.EventType);
            aParameters.Add("objectName", Target.ObjectName);
            aParameters.Add("objectId", (Target.ObjectId == null ? "" : Target.ObjectId));
            aParameters.Add("href", (Target.Href == null ? "" : Target.Href));
            wsi._Soap.AddCall("PageEvent", Safemart.Analytics.ClickReturn, aParameters);
        }
        else
        {
            //window.status = (Target.EventType != null) + "  " + Target.ObjectName + " " + Target.ObjectId +" "+ Target.Href;
            //window.status = "The object you clicked does not have an action attached to it";
        }
    }
    else
    {
        //window.status = Safemart.Analytics.PageVistId;
    }
    return true;
}

Safemart.Analytics.ClickReturn = function(returnValue)
{
    //alert(returnValue);
}
Safemart.Analytics.FindTarget = function(clicktarget)
{
    var ReturnData = new Object();
    ReturnData.ObjectName = null;
    ReturnData.ObjectId = null;
    ReturnData.EventType = null;
    ReturnData.Href = null;

    if (clicktarget.getAttribute("href") != null)
    {
        ReturnData.EventType = "href";
        ReturnData.Href = clicktarget.getAttribute("href");
    }
    else if (clicktarget.getAttribute("onclick") != null)
    {
        ReturnData.EventType = "onclick";
    }
    else if (clicktarget.tagName.toLowerCase() == "select" || clicktarget.tagName.toLowerCase() == "input")
    {
        ReturnData.EventType = "onclick";
    }

    if (ReturnData.EventType == null && typeof (clicktarget.parentNode.tagName) != 'undefined')
    {
        ReturnData = Safemart.Analytics.FindTarget(clicktarget.parentNode);
    }
    else
    {
        ReturnData.ObjectName = clicktarget.tagName;
        ReturnData.ObjectId = clicktarget.getAttribute("Id");
    }

    return ReturnData;
}

Safemart.EnableCheckAvailability = function()
{
    if (document.getElementById("BreadCrumb") != null)
    {
        var BodyHTML = document.body.innerHTML;
        var BreadCrumb = document.getElementById("BreadCrumb").innerHTML;
        if (BreadCrumb.match("Trade Products") && !BodyHTML.match("Availability: Out of Stock"))
        {
            document.getElementById("availcheck").style.display = "block";
        }
    }
}

SWH.RoundMoney = function(value)
{
    return Math.round(parseFloat(value) * 100) / 100
}

/// Converts a float value to a Money String
SWH.ToMoney = function(value, includeSign)
{

    if (typeof (includeSign) == "undefined")
    {
        includeSign = true;
    }

    // convert to string
    value = "" + value;

    if (value.indexOf(".") == -1)
    {
        value += ".00";
    }

    if (value.indexOf(".") < value.length - 3)
    {/// round to two decimals
        //value = Math.round(parseFloat(value)*100)/100

        value = Checkout.RoundMoney(value);

        /// Make the value a string again
        value = "" + value;

    }

    //alert(value + "  " + value.slice(-2,-1))
    if (value.slice(-2, -1) == ".")
    {/// second to last char is a . -- pad the value with zero.
        value += "0";
    }

    if (includeSign)
    {
        // add the $        
        value = "$" + value;
    }

    return value;
}

Safemart.Address = function()
{
    /// <summary>Basic Address Constructor</summary>
    /// <returns>Address Object</returns>
    this.InternalId = "";
    this.FirstName = "";
    this.LastName = "";
    this.Company = "";
    this.AddressLine1 = "";
    this.AddressLine2 = "";
    this.City = "";
    this.State = ""; //"AL";
    this.Zip = "";
    this.Country = ""; //"US";
    this.Phone = "";
    this.Type = ""; /// Shipping type for a purchase order
    this.Cost = 0; /// Shipping cost for a purchase order
    this.Memo = "";
    this.Raw = ""; /// The raw data string from the server.

    this.IsPhoneValid = function()
    {
        /// 99 9999 9999
        /// 999-999-9999
        /// +99 (9) 9 9999 9999
        /// (999) 999-9999
        /// 999-999-9999 ext9999
        /// 999-999-9999 ext 9999
        var _sPhoneReg = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( ext | ext)\d{1,5}){0,1}$/;

        var _oRegex = new RegExp(_sPhoneReg);
        var _bPassed = _oRegex.test(this.Phone);

        return _bPassed;
    }

    this.InvalidPhoneMsg = "Please enter a valid phone number";
}

Safemart.CreditCard = function()
{
    this.InternalId = "";
    this.Type = "Visa";
    this.NameOnCard = "";
    this.Number = "";
    this.ExpirationMonth = "";
    this.ExpirationYear = "";
    this.CVV2 = "";
}


Safemart.Item = function()
{
    this.Sku = "";
    this.Description = "";
    this.Rate = 0;
    this.Amount = 0;
}

Safemart.Transaction = function()
{
    var _xml = null;
    this.GetDate = function() { return _xml.getElementsByTagName("month")[0].firstChild.nodeValue; };
    this.OrderNumber = "";
    this.Total = "";
    this.Status = "";
    this.Items = new Array();

    this.AddItem = function(sku)
    {
        this.Items.push(new Safemart.Item());
        var _NewItem = this.Items[this.Items.length - 1];
        _NewItem.Sku = sku;
        return _NewItem;
    }


    this.Xml = function(xml)
    {
        if (typeof (xml) != "undefined")
        {
            _xml = getDomAdapter().parseXml(xml);
            //alert(getDomAdapter().serialize(_xml));
        }
        //alert(this.GetDate());
        if (_xml != null)
        {
            return _xml;
        }
    }
}

Safemart.Transactions = function()
{
    this.SalesOrders = new Array();

    this.AddSalesOrder = function(xml)
    {
        this.SalesOrders.push(new Safemart.Transaction());
        var _xNewSalesOrder = this.SalesOrders[this.SalesOrders.length - 1]
        _xNewSalesOrder.Xml(xml);

        return _xNewSalesOrder;
    }

    var _xml = null;

    this.Xml = function(xml)
    {
        if (typeof (xml) != "undefined")
        {
            _xml = getDomAdapter().parseXml(xml);

            var _xSalesOrder = _xml.getElementsByTagName("salesorder");

            for (var i = 0; i < _xSalesOrder.length; i++)
            {
                this.AddSalesOrder(getDomAdapter().serialize(_xSalesOrder[i]));
            }

            //alert(getDomAdapter().serialize(_xml));
        }

        if (_xml != null)
        {
            return _xml;
        }
    }
}

Safemart.Person = function()
{
    /// <summary>Base class for create a person</summery>
    ///<returns>Person Object</returns>
    this.SalesRep = "";
    //this.InternalID = "";
    var InternalID = "";
    this.SSN = "";
    this.Email = "";
    var HasAccount = null; /// a null = an unknown state
    this.Password = "";
    this.PassConfirm = "";
    this.Ship = new Safemart.Address();
    this.Bill = new Safemart.Address();
    this.Bill.SameAsShip = true;
    var _PaymentMethod = "";
    this.CreditCard = new Safemart.CreditCard();
    this.CreditCard.CardsOnFile = new Array();
    this.IP = "";
    this.InternalIP = false;

    /// <summary>Get or Set Internal NetSuite Id</summery>
    ///<param name="ID">(Optional) Set Internal NetSuite Id</param>
    ///<returns>Internal NetSuite Id</returns>
    this.InternalID = function(Id)
    {
        if (typeof (Id) != "undefined" && Id != null && Id.length > 0) InternalID = Id;
        return InternalID;
    }

    this.PaymentMethod = function(paymentMethod)
    {
        if (typeof (paymentMethod) != "undefined" && paymentMethod != null && paymentMethod.length > 0) _PaymentMethod = paymentMethod;
        return _PaymentMethod;
    }

    this.Transactions = new Safemart.Transactions();

    this.HasAccount = function() { return HasAccount };

    this.HasAccountCheckReturn = function(returnData)
    {
        trace = "";

        if (returnData.toLowerCase() == "false")
        {
            trace += "Account not found";
            HasAccount = false;
        }
        else
        {
            trace += " return: " + returnData;
            trace += " ID: " + InternalID;
            trace += " len: " + InternalID.length;
            HasAccount = true;

            if (returnData != "true" && InternalID.length == 0 && InternalID.indexOf("error") == -1)
            {

                InternalID = returnData;
            }
        }
        //window.status = trace;        
    }


    var _sLoginReturn = null;
    this.LoginEventHandler = function(handler)
    {
        _sLoginReturn = handler;
    }

    this.login = function()
    {
        /// <summary>Login the person</summary>
        /// <param name="callBack">Call Back Function</param>
        /// <returns>void</returns>

        document.getElementById("CheckoutNotificationCaption").innerHTML = "Customer Login";
        document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Login in progress...</center><br /><br />";
        YAHOO.example.container.panel1.show();

        var SessionID = Safemart.GetSession();

        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionID", SessionID);
        aParameters.Add("email", this.Email);
        aParameters.Add("password", this.Password);

        wsi._Soap.AddCall("CustomerLogin", _sLoginReturn, aParameters);
    }

    this.LoginPrompt = function(loginProcesser)
    {
        var _sLoginScreen = '' +
                '<div id="substepAccount" class="basicContainer-Body" style="display: block;">' +
                '<table border="0" cellspacing="5px">' +
                   '<tr>' +
                        '<td colspan="2">' +
                            '<b>To login enter your email and password.</b>' +
                        '</td>' +
                    '</tr>' +
                    '<tr>' +
                        '<td>' +
                            'Email Address:' +
                            '<br />' +
                            '<input type="text" id="LoginPromptEmail" />' +
                            '<br />' +
                            'Password:' +
                            '<br />' +
                            '<input type="password" id="LoginPromptPassword" />' +
                            '<br />' +
                        '</td>' +
                        '<td>' +
                        '</td>' +
                    '</tr>' +
                    '<tr>' +
                       '<td style="color:red;">' +
                            '<div id="LoginPromptMessage" style="visibility:hidden;">Please enter both your email address and password<div>' +
                        '</td>' +
                        '<td align="right" valign="bottom">' +
                            '<input id="LoginPromptButtonClick" type="hidden" value="" />' +
	                        '<input type="button" onclick="document.getElementById(\'LoginPromptButtonClick\').value = \'Login\'; ' + loginProcesser + ';" value="Login" />' +
	                        '&nbsp;' +
                            '<input type="button" onclick="document.getElementById(\'LoginPromptButtonClick\').value = \'Cancel\'; ' + loginProcesser + ';" value="Cancel" />' +
                        '</td>' +
                    '</tr>' +
                '</table>' +
            '</div>';

        document.getElementById("CheckoutNotificationCaption").innerHTML = "Customer Login";
        document.getElementById("CheckoutNotificationMessage").innerHTML = _sLoginScreen;
        YAHOO.example.container.panel1.show();
    }

    this.LoginPromptCallback = function()
    {
        /// reset the failure message.
        document.getElementById("LoginPromptMessage").style.visibility = "hidden";

        if (document.getElementById("LoginPromptButtonClick").value == "Cancel")
        {
            alert("You must enter a valid Email and Password to access your account");
            YAHOO.example.container.panel1.hide();
        }
        else
        {
            var _sEmail = document.getElementById("LoginPromptEmail").value;
            var _sPassword = document.getElementById("LoginPromptPassword").value;

            if (_sEmail.length > 0 && _sPassword.length > 0)
            {
                this.Email = _sEmail;
                this.Password = _sPassword;
                YAHOO.example.container.panel1.hide();

                this.login();
            }
            else
            {
                document.getElementById("LoginPromptMessage").style.visibility = "visible";
            }
        }
    }
    this.LoginCallback = function(returnData)
    {

        if (returnData.substring(0, 5) == "error")
        {
            //document.getElementById("LoginMessage").innerHTML = returnData.substring(7);
            //document.getElementById("LoginMessage").style.color = "Red";

        }
        else
        {

            //document.getElementById("substepLogin").style.display = "none";
            //Checkout.ShowStep(Checkout.Steps[1]);

            var Rows = returnData.split("||");

            for (var iRow = 0; iRow < Rows.length; iRow++)
            {
                var Fields = Rows[iRow].split("|");

                if (Rows[iRow].indexOf("Customer|") > -1)
                {
                    for (var iFields = 0; iFields < Fields.length; iFields++)
                    {
                        var Values = Fields[iFields].split("=");
                        switch (Values[0])
                        {
                            case "InternalId":
                                this.InternalID = Values[1];
                                break;

                            case "FirstName":
                                this.Ship.FirstName = Values[1];
                                break;

                            case "LastName":
                                this.Ship.LastName = Values[1];
                                break;

                            case "CompanyName":
                                this.Ship.Company = Values[1];
                                break;

                            case "Email":
                                this.Email = Values[1];
                                break;
                        }
                    }
                }

                if (Rows[iRow].indexOf("isShip=True") > 0)
                {
                    for (var iFields = 0; iFields < Fields.length; iFields++)
                    {
                        var Values = Fields[iFields].split("=");
                        switch (Values[0])
                        {

                            case "InternalId":
                                this.Ship.InternalId = Values[1];
                                break;

                            case "Addressee":
                                this.Ship.Company = Values[1];
                                break;

                            case "Attention":
                                // Override the Customer First and Last Name
                                var l_nDelimiter = Values[1].indexOf(' ');
                                var First = Values[1].substring(0, l_nDelimiter)
                                var Last = Values[1].substring(l_nDelimiter + 1, Values[1].length);

                                this.Ship.FirstName = First;
                                this.Ship.LastName = Last;
                                break;

                            case "Address1":
                                this.Ship.AddressLine1 = Values[1];
                                break;

                            case "Address2":
                                this.Ship.AddressLine2 = Values[1];
                                break;

                            case "City":
                                this.Ship.City = Values[1];
                                break;

                            case "State":
                                this.Ship.State = Values[1];
                                break;

                            case "Zip":
                                this.Ship.Zip = Values[1];
                                break;

                            case "Country":
                                this.Ship.Country = Values[1];
                                break;

                            case "Phone":
                                this.Ship.Phone = Values[1];
                                break;
                        }
                    }
                }

                if (Rows[iRow].indexOf("isBill=True") > 0 && Rows[iRow].indexOf("isShip=True") > 0)
                {
                    this.Bill.SameAsShip = true;
                }
                else if (Rows[iRow].indexOf("isBill=True") > 0)
                {
                    this.Bill.SameAsShip = false;

                    for (var iFields = 0; iFields < Fields.length; iFields++)
                    {
                        var Values = Fields[iFields].split("=");
                        switch (Values[0])
                        {
                            case "InternalId":
                                this.Bill.InternalId = Values[1];
                                break;

                            case "Addressee":
                                this.Bill.Company = Values[1]
                                break;

                            case "Attention":
                                var l_nDelimiter = Values[1].indexOf(' ');
                                var First = Values[1].substring(0, l_nDelimiter)
                                var Last = Values[1].substring(l_nDelimiter + 1, Values[1].length);

                                this.Bill.FirstName = First;
                                this.Bill.LastName = Last;
                                break;

                            case "Address1":
                                this.Bill.AddressLine1 = Values[1];
                                break;

                            case "Address2":
                                this.Bill.AddressLine2 = Values[1];
                                break;

                            case "City":
                                this.Bill.City = Values[1];
                                break;

                            case "State":
                                this.Bill.State = Values[1];
                                break;

                            case "Zip":
                                this.Bill.Zip = Values[1];
                                break;

                            case "Country":
                                this.Bill.Country = Values[1];
                                break;

                            case "Phone":
                                this.Bill.Phone = Values[1];
                                break;
                        }
                    }
                }

                if (Rows[iRow].indexOf("Card|") > -1)
                {
                    this.CreditCard.CardsOnFile[this.CreditCard.CardsOnFile.length] = Checkout._NewCard();
                    Card = this.CreditCard.CardsOnFile[this.CreditCard.CardsOnFile.length - 1];

                    for (var iFields = 0; iFields < Fields.length; iFields++)
                    {
                        var Values = Fields[iFields].split("=");
                        switch (Values[0])
                        {
                            case "InternalId":
                                Card.InternalId = Values[1];
                                break;

                            case "isDefault":
                                if (Values[1] == "true")
                                {
                                    Card.Default = true;
                                }
                                break;

                            case "Type":
                                Card.Type = Values[1];
                                break;

                            case "NameOnCard":
                                Card.NameOnCard = Values[1];
                                break;

                            case "Number":
                                Card.Number = Values[1];
                                break;

                            case "Expiration":
                                Card.Expiration = Values[1];
                                break;
                        }
                    }
                }
            }
        }
    }

    this.IsEmailValid = function()
    {

        //var _sEmailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
        //var _sEmailReg = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$";
        //var _sEmailReg = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$";
        var _sEmailReg = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
        var _oRegex = new RegExp(_sEmailReg);
        var _bPassed = _oRegex.test(this.Email);
        //
        return _bPassed;
    }

    this.IsSsnValid = function()
    {
        /// Matches 078-05-1120 | 078 05 1120 | 078051120
        /// Non-Matches 987-65-4320 | 000-00-0000 | (555) 555-5555
        var _SsnReg = /^(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -]?)(?!00)\d\d\3(?!0000)\d{4}$/;
        var _oRegex = new RegExp(_SsnReg);
        var _bPassed = _oRegex.test(this.SSN);

        return _bPassed;
    }

    this.ValidatePassword = function()
    {
        // Must be at least 6 characters
        // Must contain at least 1 number
        // Must contain at least 1 Alpha character
        //var sEmailReg = /^(?=.*\d)(?=.*[A-Za-z])\w{6,}$/; ; 

        // Original ^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$
        var sEmailReg = /^.*(?=.{6,})(?=.*\d)(?=.*[a-zA-Z]).*$/

        var oRegex = new RegExp(sEmailReg);
        var bValid = oRegex.test(this.Password);
        //window.status = bValid;
        return bValid;
        //return true;
    }
}

Safemart.FormHandler = function(formName, submitTo, submittedAt)
{
    var _FormName = formName;
    var _SubmitTo = submitTo;
    var _SubmittedAt = submittedAt;

    this.OnSubmited = function() { };
    this.OnError = function() { "", "" }; // param1 = exception; param2 = message

    this.AdvanceField = function(fromField, toField, onCharCount)
    {
        if (fromField.value.length == onCharCount)
        {
            toField.focus();
        }
    }

    this.Submit = function()
    {
        var bPassedRequired = true;
        var sFormData = "";

        for (var i = 0; i < document.getElementById(_FormName).elements.length; i++)
        {
            if (sFormData.length > 0)
            {
                sFormData += "|";
            }

            var sName = document.getElementById(_FormName).elements[i].name;
            var sTag = document.getElementById(_FormName).elements[i].tagName.toLowerCase();
            var InputType = document.getElementById(_FormName).elements[i].type.toLowerCase();
            var sValue = "";

            switch (sTag)
            {
                case "select":
                    var s = document.getElementById(_FormName).elements[i];
                    //var s = document.getElementById("citySelector");

                    /// Start with the Value
                    sValue = s.options[s.selectedIndex].value;

                    /// If the value is empty, get the text
                    if (sValue.length == 0)
                    {
                        sValue = s.options[s.selectedIndex].text;
                    }

                    break;

                default:
                    switch (InputType)
                    {
                        case "checkbox":
                            sValue = (document.getElementById(_FormName).elements[i].checked ? "T" : "F");
                            break;

                        default:
                            sValue = document.getElementById(_FormName).elements[i].value;
                    }
            }

            /// add parameters to the subject line
            var sSubjectParam = document.getElementById(_FormName).elements[i].getAttribute("subjectparam")

            if (sSubjectParam != null && sSubjectParam.toLowerCase() == "true")
            {
                _SubmittedAt += " - " + sValue;
            }

            sFormData += sName + " = " + sValue;

            sReqired = document.getElementById(_FormName).elements[i].getAttribute("required");

            if (sReqired != null && sReqired.toLowerCase() == "true")
            {
                switch (InputType)
                {
                    case "checkbox":
                        //if (!sValue)
                        if (sValue == "F")
                        {
                            bPassedRequired = false;
                        }

                    default:
                        if (document.getElementById(_FormName).elements[i].value.length == 0 || document.getElementById(_FormName).elements[i].value == document.getElementById(_FormName).elements[i].getAttribute('promptText'))
                        {
                            bPassedRequired = false;
                        }
                }

                if (!bPassedRequired)
                {
                    break;
                }
            }
        }
        
        if (bPassedRequired)
        {
            if (_SubmitTo.length > 0)
            {
                var aParameters = new wsi._Parameters();
                aParameters.Add("submitTo", _SubmitTo);
                aParameters.Add("submitedAt", _SubmittedAt);
                aParameters.Add("formData", sFormData);
                wsi._Soap.AddCall("SubmitForm", this.OnSubmited, aParameters);
            }
        }
        else
        {
            this.OnError("SubmissionError", "Please complete all required fields");
        }

        return bPassedRequired;
    }
}

Safemart.FormHandler.findElement = function (formObject, search)
{

    var ReturnElement = null;
    var i = 0;
    while (i < formObject.elements.length && formObject.elements[i].name != search)
    {

        ++i;
    }

    if (i == formObject.elements.length)
    {
        ReturnElement = null;
    }
    else
    {
        ReturnElement = formObject.elements[i]
    }

    return ReturnElement;
}

/// Use this class to submit a customer online form - the parameters are:
///     formToSubmit is the Id of the form to be submitted
///     redirect is the URL that will be displayed on a successful submission (use JavasScript: to call a functions)
///     opportunity is the name of the opportunity associated with the form
///     submissionId is the NetSuite form string
///     submitBtnId is either null or the Id for the object (button) to hide while submitting
///     progressIndicatorId is either null or the Id for the object to be displayed while submitting
/// 
/// Call Submit to send the form. Lend Gen fields are auto-added to the form before submitting, errors are
/// re-submitted for logging. If the form includes any of the following fields: firstname, lastname, phone and email.
/// each respective value will be added to cookies. If the NextBee referal cookie is found the referal field is also 
/// added to the form.
Safemart.CustomerForm = function (formToSubmit, redirect, opportunity, submissionId, submitBtnId, progressIndicatorId)
{
    var formId = formToSubmit;
    var FormObject = document.getElementById(formId);
    var RedirectUrl = redirect;
    var OpportunityText = opportunity;
    var SubmitId = submissionId;
    var BtnId = submitBtnId;
    var ProgressId = progressIndicatorId;

    var Referred_Error = false;
    var SubmittedForm = null;
    var ErrorSubmitted = false;
    var ErrorMsg = "";

    var leadsource = null;
    var custentitylead_source_create_opp = null;
    var custentitykeyword_string_create_opp = null;
    var custentitycustentity_keywordstring = null;
    var custentitypage_source_create_opportunity = null;
    var custentity_pagesource = null;

    this.Submit = function ()
    {

        var Firstname = Safemart.FormHandler.findElement(FormObject, "firstname");
        var Lastname = Safemart.FormHandler.findElement(FormObject, "lastname");
        var Phone = Safemart.FormHandler.findElement(FormObject, "phone");
        var Email = Safemart.FormHandler.findElement(FormObject, "email");

        if (Email != null) wsi._Cookie.SaveCrumb("monitoring_email", Email.value);
        if (Firstname != null) wsi._Cookie.Firstname(Firstname.value);
        if (Lastname != null) wsi._Cookie.Lastname(Lastname.value);
        if (Phone != null) wsi._Cookie.Phone(Phone.value);
        if (Email != null) wsi._Cookie.Email(Email.value);

        if (ProgressId != null || document.getElementById(ProgressId) != null)
        {
            document.getElementById(ProgressId).style.display = 'inline';
        }

        if (BtnId != null || document.getElementById(BtnId) != null)
        {
            document.getElementById(BtnId).style.display = 'none';
        }

        SetLead();
        Resubmit();
    }

    Resubmit = function ()
    {
        /// nextbee code starts
        if (!Referred_Error)
        {
            if (typeof (NextBee) != "undefined")
            {
                var referrer_customer_id_val = null;
                referrer_customer_id_val = NextBee.Common.getSessionCookie("referrer_customer_id", 548);

                if (referrer_customer_id_val != null)
                {
                    var hidden_referrer_customer_id = NextBee.Common.createElementBee("<input type='hidden' value='" + referrer_customer_id_val + "' id='custentity_referred_by' name='custentity_referred_by'>");
                    document.getElementById(formId).appendChild(hidden_referrer_customer_id);
                }
            }
        }
        else
        {
            if (document.getElementById("custentity_referred_by") != null)
            {
                /// Clear the referred by field
                document.getElementById("custentity_referred_by").value = "";
            }

            if (typeof (NextBee) != "undefined")
            {
                var ReferralName = document.getElementById("ReferralName").value;

                if (document.getElementById("custentity23") == null)
                {
                    var hidden_referrer_customer_name = NextBee.Common.createElementBee("<input type='hidden' value=' Referred By " + ReferralName + "' id='custentity23' name='custentity23'>");
                    document.getElementById(formId).appendChild(hidden_referrer_customer_name);
                }
                else
                {
                    document.getElementById("custentity23").value = ReferralName;
                }
            }

            YAHOO.example.container.panel1.hide();
        }
        /// nextbee code ends



        if (ErrorSubmitted)
        {
            var NewForm = new Safemart.FormHandler(formId, "form.error", document.location.href + "|" + ErrorMsg);
        }
        else
        {
            var NewForm = new Safemart.FormHandler(formId, "online customer form", SubmitId);
        }


        NewForm.OnSubmited = Submitted;
        NewForm.OnError = SubmitError;
        NewForm.Submit();
    }


    SubmitError = function (exception, message)
    {
        var UnhandledExceptions = new Array();
        UnhandledExceptions[0] = "phone";
        UnhandledExceptions[1] = "email";

        var DefaultPageSource = "";
        var DefaultLeadSource = "-6";
        var DefaultKeyword = "";

        if (message.indexOf("custentity_pagesource") > -1 && custentity_pagesource.value != DefaultPageSource)
        {
            custentity_pagesource.value = DefaultPageSource;
            Resubmit();
        }
        else if ((message.indexOf("leadsource") > -1 || message.indexOf("custentitylead_source_create_opp") > -1) && leadsource.value != DefaultLeadSource)
        {
            leadsource.value = DefaultLeadSource;
            custentitylead_source_create_opp.value = DefaultLeadSource;
            Resubmit();
        }
        else if ((message.indexOf("custentitykeyword_string_create_opp") > -1 || message.indexOf("custentitycustentity_keywordstring") > -1) && custentitykeyword_string_create_opp.value != DefaultKeyword)
        {
            custentitykeyword_string_create_opp.value = DefaultKeyword;
            custentitycustentity_keywordstring.value = DefaultKeyword;
            Resubmit();
        }
        else if (message.indexOf("custentity_referred_by") > -1)
        {
            Referred_Error = true;
            document.getElementById("uiVid").style.visibility = "hidden";
            YAHOO.example.container.panel1.show();
        }
        else
        {
            var Unhandled = false;
            for (var i = 0; i < UnhandledExceptions.length; i++)
            {
                if (message.indexOf(UnhandledExceptions[i]) > -1)
                {
                    Unhandled = true;
                    break;
                }
            }
            if (exception == "SubmissionError" || Unhandled)
            {
                ClearProgressIndicator();
            }
            else if (ErrorSubmitted)
            {
                Redirect();
            }
            else
            {
                ErrorSubmitted = true;
                ErrorMsg = message;
                setTimeout("Resubmit()", 1000);
            }
        }
    }

    Submitted = function (returnValue)
    {
        if (returnValue.indexOf("Error:") > -1)
        {
            SubmitError("Error", returnValue.substring(6, returnValue.length));
        }
        else
        {
            Redirect();
        }
    }

    ClearProgressIndicator = function ()
    {
        if (ProgressId != null || document.getElementById(ProgressId) != null)
        {
            document.getElementById(ProgressId).style.display = 'none';
        }

        if (BtnId != null || document.getElementById(BtnId) != null)
        {
            document.getElementById(BtnId).style.display = 'inline';
        }
    }

    Redirect = function ()
    {
        if (RedirectUrl.toLowerCase().indexOf("javascript:") == 0)
        {
            eval(RedirectUrl.slice("javascript:".length));
        }
        else
        {
            window.location = RedirectUrl;
        }
    }

    SetLead = function ()
    {
        var Lead = "-6"; /// safemart.com
        var Keyword = ""

        if (gaCookies != null)
        {
            var gac = new gaCookies();
            var CampaignContent = gac.getCampaignContent();
            CampaignTerm = gac.getCampaignTerm();
            if (CampaignContent != null && CampaignContent.length > 0)
            {
                Lead = CampaignContent;
            }

            if (CampaignTerm != null && CampaignTerm.length > 0)
            {
                Keyword = CampaignTerm;
            }
        }

        var InputType = "hidden";



        if (leadsource == null)
        {
            if (document.getElementById("leadsource" + formId) == null)
            {
                leadsource = document.createElement("input");
                leadsource.setAttribute("id", "leadsource" + formId);
                leadsource.setAttribute("name", "leadsource");
                leadsource.setAttribute("required", "false");
                leadsource.setAttribute("type", InputType);
                document.getElementById(formId).appendChild(leadsource);
            }
            else
            {
                leadsource = document.getElementById("leadsource" + formId);
            }
        }

        if (custentitylead_source_create_opp == null)
        {
            if (document.getElementById("custentitylead_source_create_opp" + formId) == null)
            {
                custentitylead_source_create_opp = document.createElement("input");
                custentitylead_source_create_opp.setAttribute("id", "custentitylead_source_create_opp" + formId);
                custentitylead_source_create_opp.setAttribute("name", "custentitylead_source_create_opp");
                custentitylead_source_create_opp.setAttribute("required", "false");
                custentitylead_source_create_opp.setAttribute("type", InputType);
                document.getElementById(formId).appendChild(custentitylead_source_create_opp);
            }
            else
            {
                custentitylead_source_create_opp = document.getElementById("custentitylead_source_create_opp" + formId);
            }
        }

        if (custentitykeyword_string_create_opp == null)
        {
            if (document.getElementById("custentitykeyword_string_create_opp" + formId) == null)
            {
                custentitykeyword_string_create_opp = document.createElement("input");
                custentitykeyword_string_create_opp.setAttribute("id", "custentitykeyword_string_create_opp" + formId);
                custentitykeyword_string_create_opp.setAttribute("name", "custentitykeyword_string_create_opp");
                custentitykeyword_string_create_opp.setAttribute("required", "false");
                custentitykeyword_string_create_opp.setAttribute("type", InputType);
                document.getElementById(formId).appendChild(custentitykeyword_string_create_opp);
            }
            else
            {
                custentitykeyword_string_create_opp = document.getElementById("custentitykeyword_string_create_opp" + formId);
            }
        }


        if (custentitycustentity_keywordstring == null)
        {
            if (document.getElementById("custentitycustentity_keywordstring" + formId) == null)
            {
                custentitycustentity_keywordstring = document.createElement("input");
                custentitycustentity_keywordstring.setAttribute("id", "custentitycustentity_keywordstring" + formId);
                custentitycustentity_keywordstring.setAttribute("name", "custentitycustentity_keywordstring");
                custentitycustentity_keywordstring.setAttribute("required", "false");
                custentitycustentity_keywordstring.setAttribute("type", InputType);
                document.getElementById(formId).appendChild(custentitycustentity_keywordstring);
            }
            else
            {
                custentitycustentity_keywordstring = document.getElementById("custentitycustentity_keywordstring" + formId);
            }
        }

        if (custentitypage_source_create_opportunity == null)
        {
            if (document.getElementById("custentitypage_source_create_opportunity" + formId) == null)
            {
                custentitypage_source_create_opportunity = document.createElement("input");
                custentitypage_source_create_opportunity.setAttribute("id", "custentitypage_source_create_opportunity" + formId);
                custentitypage_source_create_opportunity.setAttribute("name", "custentitypage_source_create_opportunity");
                custentitypage_source_create_opportunity.setAttribute("required", "false");
                custentitypage_source_create_opportunity.setAttribute("type", InputType);
                document.getElementById(formId).appendChild(custentitypage_source_create_opportunity);
            }
            else
            {
                custentitypage_source_create_opportunity = document.getElementById("custentitypage_source_create_opportunity" + formId);
            }
        }

        if (custentity_pagesource == null)
        {
            if (document.getElementById("custentity_pagesource" + formId) == null)
            {
                custentity_pagesource = document.createElement("input");
                custentity_pagesource.setAttribute("id", "custentity_pagesource" + formId);
                custentity_pagesource.setAttribute("name", "custentity_pagesource");
                custentity_pagesource.setAttribute("required", "false");
                custentity_pagesource.setAttribute("type", InputType);
                document.getElementById(formId).appendChild(custentity_pagesource);
            }
            else
            {
                custentity_pagesource = document.getElementById("custentity_pagesource" + formId);
            }
        }

        leadsource.value = Lead;
        custentitylead_source_create_opp.value = Lead;
        custentitykeyword_string_create_opp.value = Keyword;
        custentitycustentity_keywordstring.value = Keyword;
        custentitypage_source_create_opportunity.value = OpportunityText;
        custentity_pagesource.value = OpportunityText;
    }
}


Safemart.QueryString = function()
{
    var _QueryList = document.location.search.substring(1).split("&");

    this.Find = function(param)
    {
        param += "=";
        var i = _QueryList.findAt(param, 0, "contains");
        var value = null; /// default return value
        if (i != -1)
        {
            var delimiter = param.length;
            value = _QueryList[i].substring(delimiter);
        }

        return value;
    }
}

Safemart.SmartMoneyPageHandler = function()
{
    var NoFreeShipping = "false";
    var FlatRateShipping = "0";

    this.MainProductData = "SmartMoneyProductData";
    this.MainProductPrice = 38.95;
    this.Discount = 0.00;

    CheckRequired = function()
    {
        var i = 0;
        var Continue = true;
        var ElementType = "AddOn";
        do
        {
            ++i;
            var AddOn = document.getElementById(ElementType + i);

            if (AddOn == null)
            {
                if (ElementType == "AddOn")
                {
                    /// Move on to Coupons
                    i = 0;
                    ElementType = "Coupon";
                }
                else if (ElementType == "Coupon")
                {
                    /// Move on to Comments
                    i = 0;
                    ElementType = "Comment";
                }
                else
                {
                    /// Done
                    Continue = false;
                }
            }
            else
            {
                var ElementValue = document.getElementById(ElementType + i).value;
                var RequiredText = document.getElementById(ElementType + i).getAttribute("requiredtext");

                if (ElementValue == "nonoption" && RequiredText != null)
                {
                    alert(RequiredText);
                    return false;
                }
            }

        } while (Continue);

        return true;
    }

    this.ShowTerms = function()
    {
        if (CheckRequired())
        {
            document.getElementById("NotificationCaption").innerHTML = document.getElementById("uiTermsCaption").innerHTML;
            document.getElementById("NotificationBody").innerHTML = document.getElementById("uiTermsNotification").innerHTML;
            YAHOO.example.container.panel1.show();
        }
    }

    this.VerifyConditions = function()
    {
        if (document.getElementById("uiTermsAgree").checked && document.getElementById("uiCreditCheckAgree").checked)
        {
            document.getElementById("uiAccept").disabled = false;
        }
        else
        {
            document.getElementById("uiAccept").disabled = true;
        }
    }

    this.TermsAccepted = function()
    {
        this.AddItemsToCart();

    }

    this.TermsDeclined = function()
    {
        this.HideTerms();
    }

    this.HideTerms = function()
    {
        YAHOO.example.container.panel1.hide();
    }

    this.ShowDetails = function()
    {
        YAHOO.example.container.overlay1.cfg.setProperty("context", ["uiExtrasDetails", "tl", "bl"]);
        YAHOO.example.container.overlay1.setBody(document.getElementById("ExtrasOverlay").innerHTML);
        YAHOO.example.container.overlay1.show();
    }

    this.HideDetails = function()
    {
        YAHOO.example.container.overlay1.hide()
    }

    var DefaultOverlayText = "";
    ClearOverlay = function()
    {
        /// Before the Overlay is cleared get the default text
        if (DefaultOverlayText.length == 0)
        {
            DefaultOverlayText = document.getElementById("ExtrasOverlay").innerHTML;
        }

        document.getElementById("ExtrasOverlay").innerHTML = DefaultOverlayText;
    }


    this.AddItemsToCart = function()
    {
        if (CheckRequired())
        {
            var SessionID = Safemart.GetSession();

            if (SessionID.length > 0)
            {
                document.getElementById("NotificationCaption").innerHTML = document.getElementById("uiAddtoCartCaption").innerHTML;
                document.getElementById("NotificationBody").innerHTML = document.getElementById("uiAddToCartNotification").innerHTML;
                YAHOO.example.container.panel1.show();

                var CartData = "";
                if (this.MainProductData == "SmartMoneyProductData")
                {
                    /// Backward compatibility with the smart-money page
                    CartData = document.getElementById(this.MainProductData).value + "|" + document.location.href + "|" + NoFreeShipping + "|" + FlatRateShipping;
                }
                else
                {
                    /// Forward compatibility with the commerce page handler
                    CartData = this.MainProductData + "|" + document.location.href + "|" + NoFreeShipping + "|" + FlatRateShipping;
                }

                ItemCount += 1;

                var aParameters = new wsi._Parameters();
                aParameters.Add("sessionID", SessionID);
                aParameters.Add("cartData", CartData);

                wsi._Soap.AddCall("SaveToCart", this.CartReturn, aParameters);


                var i = 0;
                ContinueLoop = true;
                do
                {
                    ++i;
                    var AddOn = document.getElementById("AddOn" + i);

                    if (AddOn == null)
                    {
                        ContinueLoop = false;
                    }
                    else
                    {
                        CartData = document.getElementById("AddOn" + i).value;
                        if (CartData.length > 0)
                        {
                            ItemCount += 1;
                            //window.status = ItemCount;

                            CartData += "|" + document.location.href + "|" + NoFreeShipping + "|" + FlatRateShipping;

                            var aParameters = new wsi._Parameters();
                            aParameters.Add("sessionID", SessionID);
                            aParameters.Add("cartData", CartData);

                            wsi._Soap.AddCall("SaveToCart", this.CartReturn, aParameters);
                        }
                    }

                } while (ContinueLoop);
            }
            else
            {
                YAHOO.example.container.panel1.hide();
                setTimeout('alert("Unable to add items to your cart.\\r\\n\\r\\nInsure you have cookies enabled and try again.")', 1000);
            }
        }
    }

    var ItemCount = 0;



    this.CartReturn = function(returnValue)
    {
        //alert(returnValue);
        ItemCount -= 1;
        // window.status = ItemCount;


        /// When all the items have been added to the cart go to the checkout page.
        if (ItemCount == 0)
        {


            document.location.href = "https://" + window.location.hostname + "/checkout.htm";
        }
    }

    this.CaculateSubtotal = function()
    {

        /// sample format
        ///284|WS4945|284|Additional Sensor|1|29.00|.25|/img/landing_pages/smart-money-detail2.jpg            

        /// reset the overlay to default.
        ClearOverlay();

        var DetailsTitle = "";
        var DetailsQty = "";
        var DetailsItemPrice = "";
        var DetailsPrice = "";

        var CostOfExtras = 0;
        var i = 0;
        ContinueLoop = true;
        do
        {
            ++i;
            var AddOn = document.getElementById("AddOn" + i);

            if (AddOn == null)
            {
                ContinueLoop = false;
            }
            else
            {
                CartData = document.getElementById("AddOn" + i).value;
                if (CartData.length > 0 && CartData != "nonoption")
                {
                    var AddOnFields = CartData.split("|");

                    /// Add the price of the addon to the extras
                    CostOfExtras += parseInt(AddOnFields[4]) * parseFloat(AddOnFields[5]);

                    if (DetailsTitle.length > 0)
                    {
                        DetailsTitle += "<br />";
                        DetailsQty += "<br />";
                        DetailsItemPrice += "<br />";
                        DetailsPrice += "<br />";
                    }

                    /// Add item to the details overlay
                    DetailsTitle += AddOnFields[3];
                    DetailsQty += AddOnFields[4];
                    DetailsItemPrice += SWH.ToMoney(parseFloat(AddOnFields[5]), true);
                    DetailsPrice += SWH.ToMoney(parseInt(AddOnFields[4]) * parseFloat(AddOnFields[5]), true);
                }
            }

        } while (ContinueLoop);

        if (DetailsTitle.length > 0)
        {
            /// Populate the Overlay
            var Template = document.getElementById("ExtrasTemplate").innerHTML;
            Template = Template.replace(/_#Title#_/, DetailsTitle);
            Template = Template.replace(/_#Qty#_/g, DetailsQty);
            Template = Template.replace(/_#ItemPrice#_/g, DetailsItemPrice);
            Template = Template.replace(/_#Price#_/g, DetailsPrice);
            document.getElementById("ExtrasOverlay").innerHTML = Template;
        }
        
        if (document.getElementById("uiDiscount") != null)
        {
            document.getElementById("uiDiscount").innerHTML = SWH.ToMoney(this.Discount, true);
        }

        document.getElementById("uiExtras").innerHTML = SWH.ToMoney(CostOfExtras, true);
        document.getElementById("uiSubtotal").innerHTML = SWH.ToMoney(this.MainProductPrice + CostOfExtras + this.Discount, true);
        
    }
}

Safemart.CommercePageHandler = function()
{
    var Base = new Safemart.SmartMoneyPageHandler();
    this.UpdateSubtotal = function(){Base.CaculateSubtotal()}
    this.AddItemsToCart = function(){Base.AddItemsToCart()}
    this.ShowDetails = function(){Base.ShowDetails()}
    this.HideDetails = function(){Base.HideDetails()}

    this.AddMainProduct = function(sku, netSuiteId, title, qty, unitPrice, unitWeight, img)
    {
        Base.MainProductData = netSuiteId + "|" + sku + "|" + netSuiteId + "|" + title + "|" + qty + "|" + unitPrice + "|" + unitWeight + "|" + img;
        Base.MainProductPrice = unitPrice;
        this.UpdateSubtotal();
    }

    this.AddDiscount = function()
    {
        if (document.getElementById("Coupon1") != null)
        {
            if (document.getElementById("Coupon1").value == "nonoption")
            {
                wsi._Cookie.Coupon("");
                Base.Discount = 0.00;
            }
            else
            {

                var CouponData = document.getElementById("Coupon1").value.split("|");
                wsi._Cookie.Coupon(CouponData[0]);
                Base.Discount = parseFloat(CouponData[1]);
            }

            this.UpdateSubtotal();
        }
    }

    this.AddComment = function()
    {
        if (document.getElementById("Comment1") != null)
        {
            if (document.getElementById("Comment1").value == "nonoption")
            {
                wsi._Cookie.CartComments("");
            }
            else
            {
                wsi._Cookie.CartComments(document.getElementById("Comment1").value);
            }
        }
    }
}
Safemart.ProductPageHandler = function ()
{
    var _MainProductCaptured = false;
    var _MainProductTitle;
    var _MainShortTitle;
    var _MainProductSku;
    var _MainProductID;
    var _MainProductPrice;
    var _MainProductYourPrice; /// contains HTMl markup
    var _MainProductWeight;
    var _MainProductImage;
    var _Addons = new Array();

    if (!_MainProductCaptured)
    {
        _MainProductCaptured = true;

        _MainProductTitle = document.getElementById("ProductTitle").innerHTML;
        _MainShortTitle = document.getElementById("ShortTitle").innerHTML;
        _MainProductSku = document.getElementById("PartNumber").innerHTML.substring(13); // remove "Part Number: "
        _MainProductID = document.getElementById("MainProductData").getAttribute("pd_nsid");
        _MainProductPrice = document.getElementById("MainProductData").getAttribute("pd_price");
        _MainProductYourPrice = document.getElementById("ProdPrice").innerHTML; /// contains HTML markup
        _MainProductWeight = document.getElementById("MainProductData").getAttribute("pd_weight");
        _MainProductImage = document.getElementById("ProductImage").src;
    }

    var UpdateYourPrice = function ()
    {


        var YourPrice = parseFloat(document.getElementById("MainProductData").getAttribute("pd_price"));

        for (var i = 0; i < _Addons.length; i++)
        {
            //AddOn = document.getElementById("AddOn"+(i+1)).value;
            AddOn = _Addons[i].value;

            if (AddOn.length > 0 && AddOn.toLowerCase() != "none" && AddOn.indexOf('REPLACEMENT') == -1)
            {
                var AddOnValues = AddOn.split("|");
                if (AddOnValues.length == 6)
                {/// If the data does not contain a sku, add a blank field
                    for (var isku = AddOnValues.length; isku > 1; isku--)
                    {
                        AddOnValues[isku] = AddOnValues[isku - 1];
                    }
                }

                AddOnValues[1] = "-"; /// replace the sku with a dash

                /// <Type>|<SKU>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<Img>|<URL>
                /// BUNDLE|4849|Power Cord - by the foot|6|0.33|1.00

                //alert(parseInt(AddOnValues[4]) * parseFloat(AddOnValues[5]))
                YourPrice += parseInt(AddOnValues[4]) * parseFloat(AddOnValues[5]);
            }


        }

        var NewPrice = SWH.ToMoney(YourPrice, false);

        var Delimit1 = _MainProductYourPrice.indexOf("Your Price: $") + 12;
        var Delimit2 = _MainProductYourPrice.indexOf(".", Delimit1) + 3;
        var OldPrice = _MainProductYourPrice.substring(Delimit1, Delimit2);
        var NewYourPrice = _MainProductYourPrice.replace(OldPrice, "$" + NewPrice);

        document.getElementById("ProdPrice").innerHTML = NewYourPrice;
    }

    var AddonCount = 0;
    var ContinueLoop = true;
    do
    {
        ++AddonCount;
        var AddOn = document.getElementById("AddOn" + AddonCount);
        //alert("AddOn"+AddonCount);
        if (AddOn == null)
        {
            ContinueLoop = false;
        }
        else
        {
            AddOnChangeEvent = document.getElementById("AddOn" + AddonCount).onchange;

            /// Replacements already have an onchange event
            /// Don't overwrite the event
            if (AddOnChangeEvent == null)
            {
                AddOn.onchange = UpdateYourPrice;
                _Addons[_Addons.length] = AddOn;
            }

        }

    } while (ContinueLoop);

    this.ReplaceProduct = function (product)
    {
        //alert(product);



        ///REPLACEMENT|1448|sku|1Touch Fingerprint Door Lock|1|249.00|1.00
        var ReplacementProduct = product.split("|");

        if (ReplacementProduct[0].length == 0 || ReplacementProduct[0].toLowerCase() == "none")
        {
            document.getElementById("ProductTitle").innerHTML = _MainProductTitle

            document.getElementById("MainProductData").setAttribute("pd_nsid", _MainProductID);
            document.getElementById("PartNumber").innerHTML = "Part Number: " + _MainProductSku; // remove "Part Number: "
            document.getElementById("ShortTitle").innerHTML = _MainShortTitle;
            document.getElementById("MainProductData").setAttribute("pd_price", _MainProductPrice);
            document.getElementById("ProdPrice").innerHTML = _MainProductYourPrice;
            document.getElementById("MainProductData").setAttribute("pd_weight", _MainProductWeight);
            //document.getElementById("ProductImage").src;        
        }
        else
        {
            //var NewPrice = parseFloat(ReplacementProduct[5])+parseFloat(_MainProductPrice);
            var NewPrice = ReplacementProduct[5];

            var Delimit1 = _MainProductYourPrice.indexOf("Your Price: $") + 13;
            var Delimit2 = _MainProductYourPrice.indexOf(".", Delimit1) + 3;
            var OldPrice = _MainProductYourPrice.substring(Delimit1, Delimit2);
            var NewYourPrice = _MainProductYourPrice.replace(OldPrice, NewPrice);

            document.getElementById("ProductTitle").innerHTML = ReplacementProduct[3]
            document.getElementById("MainProductData").setAttribute("pd_nsid", ReplacementProduct[2]);
            document.getElementById("PartNumber").innerHTML = "Part Number: " + ReplacementProduct[1]; // remove "Part Number: "
            document.getElementById("ShortTitle").innerHTML = ReplacementProduct[3];
            document.getElementById("MainProductData").setAttribute("pd_price", NewPrice);
            document.getElementById("ProdPrice").innerHTML = NewYourPrice;
            document.getElementById("MainProductData").setAttribute("pd_weight", ReplacementProduct[6]);
            //document.getElementById("ProductImage").src;
        }

        UpdateYourPrice();
    }

    this.GetSku = function ()
    {
        if (document.getElementById("PartNumber") != null)
        {
            return document.getElementById("PartNumber").innerHTML.substring(13); // remove "Part Number: "
        }
        else
        {
            return "";
        }
    }

    this.SetOverlayText = function ()
    {
        /// Populate Support Level Overlay
        var SupportLevelCount = 3;
        for (var i = 1; i <= SupportLevelCount; i++)
        {
            if (document.getElementById("supportlevel" + i) != null)
            {
                var aParameters = new wsi._Parameters();
                aParameters.Add("id", i.toString());
                aParameters.Add("textName", "overlay");
                wsi._Soap.AddCall("GetSupportLevelText", _SetOverlayTextCallback, aParameters);
                break;
            }
        }
    }

    var _SetOverlayTextCallback = function (returnValue)
    {
        if (document.getElementById('supportlevel_overlay_content') != null)
        {
            document.getElementById('supportlevel_overlay_content').innerHTML = returnValue;
        }
    }
}

// Review Class
Safemart.Review = new Object();

Safemart.Review.Customer = new Safemart.Person();

Safemart.Review.Stars = "Not Set";
// Save Review function
Safemart.Review.Save = function()
{

    _bValidated = true;

    var _sDisplayName = document.getElementById("DisplayName").value;
    var _sEmail = document.getElementById("Email").value;
    Safemart.Review.Customer.Email = _sEmail;
    var _sHeadline = document.getElementById("Headline").value;
    var _sRating = document.getElementsByName("");
    var _sReview = document.getElementById("Comments").value;

    if (_sDisplayName.length == 0) _bValidated = false;
    if (_sEmail.length == 0) _bValidated = false;
    if (_sHeadline.length == 0) _bValidated = false;
    if (_sReview.length == 0) _bValidated = false;
    if (Safemart.Review.Stars == "Not Set") _bValidated = false;


    if (!_bValidated)
    {
        document.getElementById("ReviewKickbackMessage").innerHTML = "Please complete all fields.";
    }
    else if (!Safemart.Review.Customer.IsEmailValid())
    {
        document.getElementById("ReviewKickbackMessage").innerHTML = "Please include a valid email address.";
    }
    else
    {
        document.getElementById("MyReview").style.display = "none";
        document.getElementById("ReviewThankyou").style.display = "block";
//alert(Safemart.ProductPage.GetSku() + "\r\n" + _sDisplayName + "\r\n" + _sEmail + "\r\n" + _sHeadline + "\r\n" + Safemart.Review.Stars + "\r\n" + _sReview);     
        var aParameters = new wsi._Parameters();
        aParameters.Add("productSku", Safemart.ProductPage.GetSku());
        aParameters.Add("displayName", _sDisplayName);
        aParameters.Add("email", _sEmail);
        aParameters.Add("headline", _sHeadline);
        aParameters.Add("rating", Safemart.Review.Stars);
        aParameters.Add("review", _sReview);

        wsi._Soap.AddCall("SaveReview", Safemart.Review.SaveReturn, aParameters);
    }
}

/// Save Review Callback function
Safemart.Review.SaveReturn = function(returnValue)
{
    //alert(returnValue);
    //document.getElementById("ReviewThankyou").innerHTML = returnValue;
}

/// YUI Namespace - Yahoo User Interfaces
Safemart.YUI = new Object();

/// a helper object that supports multiple overlays on a single page
Safemart.YUI.Overlay = function()
{
    /// Sample call to show an overlay
    ///ShowOverlay(1, 300, 'tl', 'tl')
    var OverlayCollection = new Array();
    var _CurrentOverlay = null;

    /// <summary>
    /// Show an overlay
    /// </summary>
    /// <param name="overlayId">The overlay Id</param>
    /// <param name="overlayWidth">The width of the overlay</param>
    /// <param name="position">The corner of the overlay that is to be anchored</param>
    /// <param name="positionTo">The corner of the anchor that the overlay is to be anchored</param>
    this.Show = function(overlayId, overlayWidth, position, positionTo, hideCurrent)
    {
        if (typeof (hideCurrent) == "undefined") hideCurrent = false;

        if (_CurrentOverlay != null)
        {
            if (hideCurrent) this.Hide(_CurrentOverlay);
        }
        /// store the current overlay so we can hide it later.
        _CurrentOverlay = overlayId;

        /// Only need to instantiate the overlay once
        //if (OverlayCollection[overlayId] == null)
        //{
        OverlayCollection[overlayId] = new YAHOO.widget.Overlay("overlay" + overlayId, { visible: false });
        OverlayCollection[overlayId].cfg.setProperty("width", overlayWidth + "px");
        //}

        /// The anchor may have moved, reset the postion
        OverlayCollection[overlayId].cfg.setProperty("context", ["overlay" + overlayId + "-anchor", position, positionTo]);

        /// Show the overlay
        OverlayCollection[overlayId].show();
    }

    /// <summary>
    /// Hide an overlay
    /// </summary>
    /// <param name="overlayId">The overlay Id</param>
    this.Hide = function(overlayId)
    {
        OverlayCollection[overlayId].hide()
    }


    /* 
    - The overlay DIV Id must use the naming convention: 'overlay' + overlayId
    - The overlay anchor naming convetion is: 'overlay' + overlayId + '-anchore'
		
			**SAMPLE OVERLAY**
		
				<div class="yui-skin-sam">
    <div id="overlay1" style="visibility:hidden; background-color:white;border:solid 1px black;">
    <div class="hd"></div>
    <div class="bd" style="padding:10px;">
    <div style="padding-bottom:10px;"><b>Edit Title</b></div>
    <asp:TextBox id="uiTitleEdit" width="275px" runat="server"></asp:TextBox>
    <br />
    <br />
    <div style="position:relative; left:180px;">
    <span onclick="YuiOverlayHelper.Hide(1)" class="edit">CANCEL</span>&nbsp;&nbsp;&nbsp;<asp:Button ID="uiTitleSave" OnClientClick="YuiOverlayHelper.Hide(1)" OnClick="uiEdit_Click" CommandName="Title" Text="Save" runat="server" />
    </div>
    </div>
    </div>
    </div>
		

    **SAMPLE ANCHOR**
			
    <span class="edit" id="overlay1-anchor" onclick="YuiOverlayHelper.Show(1, 300, 'tl', 'tl')">EDIT</span>
		
		*/
}

function getDomAdapter()
{
    var adapter = '';
    if ('undefined' != typeof ActiveXObject)
    {
        adapter = 'MS';
    } else if ('undefined' != typeof document
		&& document.implementation
		&& document.implementation.createDocument
		&& 'undefined' != typeof DOMParser)
    {
        adapter = 'default';
    }
    switch (adapter)
    {
        case 'MS':
            return new (function()
            {
                this.createDocument = function()
                {
                    var names = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];
                    //var names = ["Microsoft.XMLDOM"];
                    //var names = ["Microsoft.XMLDOM"];
                    for (var key in names)
                    {
                        try
                        {
                            return new ActiveXObject(names[key]);
                        } catch (e) { }
                    }
                    throw new Error('Unable to create DOMDocument');
                };
                this.serialize = function(doc)
                {
                    return doc.xml;
                };
                this.parseXml = function(xml)
                {
                    var doc = this.createDocument();
                    if (!doc.loadXML(xml))
                    {
                        throw new Error('Parse error');
                    }
                    //return doc.documentElement;
                    return doc
                };
            })();
        case 'default':
            return new (function()
            {
                this.createDocument = function()
                {
                    return document.implementation.createDocument("", "", null);
                };
                this.serialize = function(doc)
                {
                    return new XMLSerializer().serializeToString(doc);
                };
                this.parseXml = function(xml)
                {
                    var doc = new DOMParser().parseFromString(xml, "text/xml");
                    if ("parsererror" == doc.documentElement.nodeName)
                    {
                        throw new Error('Parse error');
                    }
                    return doc;
                };
            })();
        default:
            throw new Error('Unable to select the DOM adapter');
    }
};


/******************************************
*                                         *
*                 WSI                     *
*         Web Service Interface           *
*                                         *
*******************************************/

wsi = new Object();

wsi.GetIP = function(returningFunction)
{
    var aParameters = new wsi._Parameters();
    wsi._Soap.AddCall("GetIpAddress", returningFunction, aParameters);
}

wsi.Configuration = function(key, returningFunction)
{
    var aParameters = new wsi._Parameters();
    aParameters.Add("key", key);
    wsi._Soap.AddCall("Configuration", returningFunction, aParameters);
}

wsi.GetServerTime = function(returningFunction)
{
    var aParameters = new wsi._Parameters();
    wsi._Soap.AddCall("ServerTime", returningFunction, aParameters);
}

wsi.GetKey = function(returningFunction)
{
    var aParameters = new wsi._Parameters();
    wsi._Soap.AddCall("GetKey", returningFunction, aParameters);
}

/// Warning: Getting a new session Id is an asynchronous funtion
wsi.GetNewSessionId = function()
{
    /// if a session id has not been established, get one.
    if (Safemart.GetSession() == "")
    {
        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")
    {
        //alert(CartData);
        wsi.Cart.Save(CartData);
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        Checkout.CartProcessor.AddToCart(CartData)
        wsi.Cart.GetViewText();
    }
}

wsi.Cart.NewCartItem = function(sku, netSuiteId, title, qty, unitPrice, unitWeight, img, url)
{
    ///<GroupId or Type>|<SKU>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<Img>|<URL>|<No Free Shipping>|<Flat Rate Shipping>
    ///ADD-ON|-|1525|1 Year Manufacturer Warranty|1|0.00|1.00|-|-|false|0.00
    var _Type = "MainProduct";
    var _Sku = sku;
    var _NetSuiteId = netSuiteId;
    var _Title = title;
    var _Qty = qty;
    var _UnitPrice = unitPrice;
    var _UnitWeight = unitWeight;
    var _Img = img;
    var _Url = url;
    var _NoFreeShip = "false";
    var _FlatRateShip = "0.00";
    var _CartName = "";

    this.Type = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _Type = newValue;
        }

        return _Type;
    }

    this.Sku = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _Sku = newValue;
        }

        return _Sku;
    }

    this.NetSuiteId = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _NetSuiteId = newValue;
        }

        return _NetSuiteId;
    }

    this.Title = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _Title = newValue;
        }

        return _Title;
    }

    this.Qty = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _Qty = newValue;
        }

        return _Qty;
    }

    this.UnitPrice = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _UnitPrice = newValue;
        }

        return _UnitPrice;
    }

    this.UnitWeight = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _UnitWeight = newValue;
        }

        return _UnitWeight;
    }

    this.Img = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _Img = newValue;
        }

        return _Img;
    }

    this.Url = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _Url = newValue;
        }

        return _Url;
    }

    this.NoFreeShip = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _NoFreeShip = newValue;
        }

        return _NoFreeShip;
    }

    this.FlatRateShipping = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _FlatRateShip = newValue;
        }

        return _FlatRateShip;
    }

    this.CartName = function(newValue)
    {
        if (typeof (newValue) != "undefined")
        {
            _CartName = newValue;
        }

        return _CartName;
    }

    var _Options = new Array();

    this.NewAddOn = function(type, netSuiteId, title, qty, unitPrice, unitWeight)
    {
        //BUNDLE|4849|Power Cord Length in Feet|6|0.33|1.00
        //sku, netSuiteId, title, qty, unitPrice, unitWeight, img, url)
        var Option = new wsi.Cart.NewCartItem("-", netSuiteId, title, qty, unitPrice, unitWeight, "-", "-");
        Option.Type(type);

        _Options[_Options.length] = Option;
    }

    this.Serialize = function()
    {
        
        var GroupId = _NetSuiteId

        var Options = "";

        for (var i = 0; i < _Options.length; i++)
        {
            var SerializedTitle = ""
            if (_Options[i].Qty() != "1")
            {
                SerializedTitle = "Qty " + _Options[i].Qty() + " - " + _Options[i].Title();
            }
            else
            {
                SerializedTitle = _Options[i].Title();
            }


            /// We need one addon for each Main Products
            var SerializedQty = _Qty * parseInt(_Options[i].Qty());


            Options += "|" + _Options[i].Type() + "|" + _Options[i].Sku() + "|" + _Options[i].NetSuiteId() + "|" + SerializedTitle + "|" + SerializedQty + "|"
                        + _Options[i].UnitPrice() + "|" + _Options[i].UnitWeight() + "|" + _Options[i].Img() + "|" + _Options[i].Url() + "|"
                        + _Options[i].NoFreeShip() + "|" + _Options[i].FlatRateShipping();

            GroupId += "-" + _Options[i].Qty() + ":" + _Options[i].NetSuiteId();
        }
        
        var MainProduct = GroupId + "|" + _Sku + "|" + _NetSuiteId + "|" + _Title + "|" + _Qty + "|" + _UnitPrice +
                        "|" + _UnitWeight + "|" + _Img + "|" + _Url + "|" + _NoFreeShip + "|" + _FlatRateShip;
        
        return MainProduct + Options;
    }
}

wsi.Cart.CallBack = null;

/// Server Based cart
wsi.Cart.Save = function(cartData, callBack)
{
    if (document.getElementById("CartItemCount") != null)
    {
        if (document.getElementById("CartItemCount").innerHTML == "0")
        {
            //if (typeof (pageTracker) != "undefined")
            if (typeof (_gaq) != "undefined")
            {
                //pageTracker._trackPageview("/firstaddtocart");
                _gaq.push(['_trackPageview', '/firstaddtocart']);
            }
        }
    }

    //if (typeof (callBack) == "undefined") callBack = wsi.Cart.SaveReturn;
    if (typeof (callBack) != "undefined") wsi.Cart.CallBack = callBack;

    var Cart = "";
    var CartName = "";

    if (typeof (cartData.Serialize) == "function")
    {
        Cart = cartData.Serialize();
        CartName = cartData.CartName();
    }
    else
    {
        Cart = cartData;
    }

    //alert(Cart);

    SessionID = Safemart.GetSession();
    SessionID += CartName;

    if (document.getElementById("trace") != null) document.getElementById("trace").innerHTML += "<br>wsi.Cart.Save SessionID " + SessionID;
    //window.clipboardData.setData("Text", cartData);

    var aParameters = new wsi._Parameters();
    aParameters.Add("sessionID", SessionID);
    aParameters.Add("cartData", Cart);


    //wsi._Soap.AddCall("SaveToCart", callBack, aParameters);
    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)
{
    if (document.getElementById("trace") != null) document.getElementById("trace").innerHTML += "<br>wsi.cart.SaveReturn returnValue " + returnValue;
    //alert(returnValue);
    var ParamArray = returnValue.split("|");
    /// The session id is now created on page load, don't overwrite
    //wsi._Cookie.SaveCrumb("SessionID", parseInt(ParamArray[0])); /// parse it, exclude the cart name
    var ParamList = ParamArray[1] + "|" + ParamArray[2];

    if (document.getElementById("trace") != null) document.getElementById("trace").innerHTML += "<br>wsi.cart.SaveReturn sessionID " + ParamArray[0] + " - " + parseInt(ParamArray[0]) + " - " + Safemart.GetSession();

    /// If the session id contains a cart name the parsed value
    /// and the unparsed value will differ.
    if (parseInt(ParamArray[0]) == ParamArray[0])
    {
        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";
        }
    }

    if (wsi.Cart.CallBack != null) wsi.Cart.CallBack(returnValue);
    //alert("Cart Saved: " + sessionID);
}

wsi.Cart.Clear = function(cartName, callback)
{
    SessionID = Safemart.GetSession();
    SessionID += cartName;

    var aParameters = new wsi._Parameters();
    aParameters.Add("sessionID", SessionID);

    wsi._Soap.AddCall("ClearCart", callback, aParameters);
}

wsi.Cart.GetViewText = function()
{
    if (Checkout.Cart.Mode == "Server")
    {
        SessionID = Safemart.GetSession();

        if (SessionID != "")
        {
            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);
    }
}

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
            {
                // FF splits the results into text nodes at 4096k chunks.
                cnt = wsi._Soap.xmlhttp.responseXML.getElementsByTagName(oCall.CallMethod + "Result")[0].childNodes;

                l_return = cnt[0].nodeValue;
                for (i = 1; i < cnt.length; i++) l_return += cnt[i].nodeValue;

                //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 " + wsi._Soap.xmlhttp.status + ": unable to retrieve 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.ClearCrumb = function(crumb)
{

    var l_dToday = new Date();
    var l_dThisYear = l_dToday.getFullYear()
    var l_dExpireDate = new Date(l_dThisYear - 1, 11, 31);
    
    document.cookie = crumb + '=;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
}

wsi._Cookie.UpdateCrumb = function(crumbname, newValue)
{
    if (typeof (newValue) != "undefined")
    {
        wsi._Cookie.SaveCrumb(crumbname, newValue);
        return newValue;
    }
    else
    {
        return (wsi._Cookie.GetCrumb(crumbname) == null ? "" : wsi._Cookie.GetCrumb(crumbname));
    }
}

wsi._Cookie.Key = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("ky", newValue);
}

wsi._Cookie.Firstname = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("fn", newValue);
}

wsi._Cookie.Lastname = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("ln", newValue);
}

wsi._Cookie.Phone = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("ph", newValue);
}

wsi._Cookie.Email = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("em", newValue);
}

wsi._Cookie.CampaignId = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("ci", newValue);
}

wsi._Cookie.Coupon = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("cp", newValue);
}

wsi._Cookie.CartComments = function(newValue)
{
    return wsi._Cookie.UpdateCrumb("cc", newValue);
}

///////// for Testing /////////////////////////////////////////

wsi._ReturnTest = function(returnMessage)
{
    alert("Return Message: " + returnMessage);
}

/******************************************
*                                         *
*               End WSI                   *
*         Web Service Interface           *
*                                         *
*******************************************/

/******************************************
*                                         *
*             Checkout Class              *
*                                         *
*                                         *
*******************************************/

// base checkout object "Class"
Checkout = new Object();

// Customer Object
Checkout.Customer = new Safemart.Person();
Checkout.Customer.LeadSource = "-6"; /// default to Safemart.com
Checkout.Customer.OpportunityType = "General - Cart"; // defaut to safemart
Checkout.Customer.CampaignKeyword = ""; // defaut to safemart
Checkout.Customer.ChampionStatus = ""; /// Extended from Base Class
Checkout.Customer.Ship.State = ""; /// Set a default value
Checkout.Customer.Ship.StateDomestic = ""; /// Extended from Base Class
Checkout.Customer.Ship.StateCanada = ""; /// Extended from Base Class
Checkout.Customer.Ship.StateInternational = ""; /// Extended from Base Class
Checkout.Customer.Ship.Country = ""; /// Set a default value
Checkout.Customer.Ship.CountryInternational = ""; /// Extended from Base Class
Checkout.Customer.Bill.State = ""; /// Set a default value
Checkout.Customer.Bill.StateDomestic = ""; /// Extended from Base Class
Checkout.Customer.Bill.StateCanada = ""; /// Extended from Base Class
Checkout.Customer.Bill.StateInternational = ""; /// Extended from Base Class
Checkout.Customer.Bill.Country = ""; /// Set a default value
Checkout.Customer.Bill.CountryInternational = ""; /// Extended from Base Class

Checkout.ShowSidebar = true;
/*
Checkout.Customer.Ship.State = "AL"; /// Set a default value
Checkout.Customer.Ship.StateDomestic = "AL"; /// Extended from Base Class
Checkout.Customer.Ship.StateCanada = ""; /// Extended from Base Class
Checkout.Customer.Ship.StateInternational = ""; /// Extended from Base Class
Checkout.Customer.Ship.Country = "US"; /// Set a default value
Checkout.Customer.Ship.CountryInternational = "US"; /// Extended from Base Class
Checkout.Customer.Bill.State = "AL"; /// Set a default value
Checkout.Customer.Bill.StateDomestic = "AL"; /// Extended from Base Class
Checkout.Customer.Bill.StateCanada = ""; /// Extended from Base Class
Checkout.Customer.Bill.StateInternational = ""; /// Extended from Base Class
Checkout.Customer.Bill.Country = "US"; /// Set a default value
Checkout.Customer.Bill.CountryInternational = "US"; /// Extended from Base Class
*/


Checkout.AutoFill = function()
{
    if (Checkout.Customer.Email == "shane@safemart.com")
    {
	    Checkout.Customer.Ship.FirstName = "Shane";
	    Checkout.Customer.Ship.LastName = "Test";
	    Checkout.Customer.Ship.AddressLine1 = "123 Main";
	    Checkout.Customer.Ship.City = "Saint Marys";
	    Checkout.Customer.Ship.State = "KS";
	    Checkout.Customer.Ship.Country = "US"
	    Checkout.Customer.Ship.Zip = "66536";
	    Checkout.Customer.Ship.Phone = "(123) 123-1232"
	    Checkout.Customer.CreditCard.NameOnCard = "shane";
	    Checkout.Customer.CreditCard.Type = "Visa";
	    Checkout.Customer.CreditCard.Number = "4111111111111111";
	    Checkout.Customer.CreditCard.ExpirationMonth = "12";
	    Checkout.Customer.CreditCard.ExpirationYear = "16";
	    Checkout.Customer.CreditCard.CVV2 = "123";



        document.getElementById("txtShipFirstName").value = Checkout.Customer.Ship.FirstName;
        document.getElementById("txtShipLastName").value = Checkout.Customer.Ship.LastName;
        document.getElementById("txtShipAddress1").value = Checkout.Customer.Ship.AddressLine1;
        document.getElementById("txtShipCity").value = Checkout.Customer.Ship.City;
        Checkout.Customer.Ship.StateDomestic = Checkout.Customer.Ship.State;
        Checkout.SetStateField("Ship");
        document.getElementById("txtShipZipPostalCode").value = Checkout.Customer.Ship.Zip;
        document.getElementById("optShipCountryId").value = Checkout.Customer.Ship.Country;


        ClearInputExample(document.getElementById("txtShipPhoneNumber"))

        var PhoneNumber = Checkout.Customer.Ship.Phone;
        PhoneNumber = PhoneNumber.replace("-", " ").replace("(", "").replace(")", "");
        var PhoneArray = PhoneNumber.split(" ");

        document.getElementById("txtShipPhoneArea").value = PhoneArray[0];
        document.getElementById("txtShipPhonePrefix").value = PhoneArray[1];
        document.getElementById("txtShipPhoneSuffix").value = PhoneArray[2];

        document.getElementById("txtShipPhoneNumber").value = Checkout.Customer.Ship.Phone;



        document.getElementById("txtFirstNameOnCard").value = Checkout.Customer.CreditCard.NameOnCard;
        document.getElementById("lstCardType").value = Checkout.Customer.CreditCard.Type;
        document.getElementById("txtCardNumber").value = Checkout.Customer.CreditCard.Number;
        document.getElementById("intMonth").value = Checkout.Customer.CreditCard.ExpirationMonth;
        document.getElementById("intYear").value = Checkout.Customer.CreditCard.ExpirationYear;
        document.getElementById("txtCWCode").value = Checkout.Customer.CreditCard.CVV2;

    }
}

Safemart.FetchBackBase = function()
{
    var _Enabled = false;
    var _Url = "https://pixel.fetchback.com/serve/fb/pdj?cat=&name=landing&sid=1347";
    var _Frame = "uiFetchbackPixel"

    this.Abandon = function(productList)
    {
        if (_Enabled)
        {
            var Pixel = document.getElementById(_Frame);
            if (Pixel != null)
            {
                Pixel.src = _Url + "&abandon_products=" + productList;
            }
        }
    }

    this.Purchase = function(productList)
    {
        if (_Enabled)
        {
            var Pixel = document.getElementById(_Frame);
            if (Pixel != null)
            {
                Pixel.src = _Url + "&purchase_products=" + productList;
            }
        }
    }
}

Checkout.FetchBack = new Safemart.FetchBackBase();
Checkout.FetchBack.FetchBackPurchaseList = "";


Safemart.CommissionJunctionPixelBase = function()
{
    var _Enabled = true;
    var _Url = "[[protocol]]//www.emjcd.com/u?CID=1520777&OID=[[OrderNumber]]&TYPE=345264&[[items]]&CURRENCY=USD&METHOD=IMG";
    var _Items = new Array();

    this.AddItem = function(id, amount, qty)
    {
        if (_Enabled)
        {
            if (amount.indexOf(".") == -1) amount += ".00";
            _Items[_Items.length] = "ITEM{0}={1}&AMT{0}={2}&QTY{0}={3}".replace(/\{0\}/g,_Items.length+1).replace("{1}",id).replace("{2}",amount).replace("{3}", qty);
        }
    }

    this.ClearItems = function()
    {
        if (_Enabled)
        {
            _Items = new Array();
        }
    }

    this.PostPixel = function(orderNumber)
    {
        if (_Enabled)
        {
		    if (document.getElementById("emjcd") != null)
		    {
			    var Src =  _Url.replace("[[protocol]]", document.location.protocol).replace("[[OrderNumber]]",orderNumber).replace("[[items]]",_Items.join("&"));
		        document.getElementById("emjcd").setAttribute("src",Src);
		    }
        }
    }
}

Checkout.CommissionJunctionPixel = new Safemart.CommissionJunctionPixelBase();

Safemart.PayPalBase = function()
{
    var _Enabled = true;
    var _GetDetailReturnHandler;
    var _PlaceOrderReturnHandel;
    var _ErrorResponse = "";
    var _ValidShipping = "true";
    var _ShippingAddress = "";
    var _ShipTotal = 0;


    this.Enabled = function()
    {
        return _Enabled;
    }

    this.DoCheckout = function()
    {
        _Notification("checkout");
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", Safemart.GetSession());
        wsi._Soap.AddCall("PayPalCheckout", _DoCheckoutCallback, aParameters);

    }

    var _Notification = function(whichOverlay)
    {

        if (document.getElementById("PayPalPanel") == null)
        {
            var PayPalPanel = document.createElement("div");
            document.body.appendChild(PayPalPanel);
            PayPalPanel.setAttribute('id', "PayPalPanel");
            PayPalPanel.setAttribute('visibility', 'hidden');
            PayPalPanel.setAttribute('style', 'background-color:white');

            //<div class="hd" id="eBillCaption" ></div>
            YAHOO.example.container.PayPalPanel = new YAHOO.widget.Panel("PayPalPanel",
			     { fixedcenter: true,
			         visible: false,
			         width: "400px",
			         height: "150px",
			         zIndex: 1000,
			         close: false,
			         modal: true,
			         effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: .5 }
			     });
            YAHOO.example.container.PayPalPanel.render();
        }

        var PayPalDiv = document.getElementById("PayPalPanel")
        switch (whichOverlay)
        {
            case "checkout":
                PayPalDiv.innerHTML = "<div class='bd' style='background-color:white;'><br /><br /><center>Preparing your cart for PayPal.<br /><img src='/img/images/progress.gif' alt='' style='padding-top:10px;'></center><br /><br /></div>";
                break;

            case "placeorder":
                PayPalDiv.innerHTML = "<div class='bd' style='background-color:white;'><br /><br /><center>Submitting order.<br /><img src='/img/images/progress.gif' alt='' style='padding-top:10px;'></center><br /><br /></div>";
                break;
        }
        YAHOO.example.container.PayPalPanel.show();
    }

    var _HideNotification = function()
    {
        YAHOO.example.container.PayPalPanel.hide();
    }
    var _DoCheckoutCallback = function(returnValue)
    {
        if (returnValue.indexOf("Error") > -1)
        {
            _HideNotification();
            returnValue = returnValue.replace("Error: ", "");
            alert(returnValue);
        }
        else
        {
            document.location.href = returnValue;
        }

    }

    this.GetDetails = function(returnHandler)
    {
        _GetDetailReturnHandler = returnHandler;
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", Safemart.GetSession());
        wsi._Soap.AddCall("PayPalGetDetails", _GetDetailCallback, aParameters);
    }

    var _GetDetailCallback = function(returnValue)
    {


        var isSuccessful = true;
        if (returnValue.indexOf("Error") > -1)
        {
            _ErrorResponse = returnValue.replace("Error: ", "");
            isSuccessful = false;
        }
        else
        {
            //_PreAuthReturn = getDomAdapter().parseXml(returnValue);
            if ('undefined' != typeof ActiveXObject)
            {
                // _XmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                _ShippingAddress = new ActiveXObject("Microsoft.XMLDOM");
                _ShippingAddress.loadXML(returnValue);

            }
            else
            {
                _ShippingAddress = getDomAdapter().parseXml(returnValue);
            }
            _ValidShipping = _ShippingAddress.getElementsByTagName("validshipping")[0].firstChild.nodeValue;
            _ShipTotal = _ShippingAddress.getElementsByTagName("shiptotal")[0].firstChild.nodeValue;

        }

        _GetDetailReturnHandler(isSuccessful);
    }

    this.ValidShipping = function()
    {
        return _ValidShipping;
    }

    this.ShipTotal = function()
    {
        return _ShipTotal;
    }

    this.Address1 = function()
    {
        return _ShippingAddress.getElementsByTagName("address1")[0].firstChild.nodeValue;
    }

    this.Address2 = function()
    {
        if (_ShippingAddress.getElementsByTagName("address2")[0].firstChild == null)
        {
            return "";
        }
        else
        {
            return _ShippingAddress.getElementsByTagName("address2")[0].firstChild.nodeValue;
        }
    }

    this.City = function()
    {
        return _ShippingAddress.getElementsByTagName("city")[0].firstChild.nodeValue;
    }

    this.State = function()
    {
        return _ShippingAddress.getElementsByTagName("state")[0].firstChild.nodeValue;
    }

    this.Zip = function()
    {
        return _ShippingAddress.getElementsByTagName("zip")[0].firstChild.nodeValue;
    }

    this.Country = function()
    {
        return _ShippingAddress.getElementsByTagName("country")[0].firstChild.nodeValue;
    }

    this.PlaceOrder = function(returnHandler, shipId, shipAmount, tax, orderTotal)
    {
        _Notification("placeorder");
        _PlaceOrderReturnHandel = returnHandler;
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", Safemart.GetSession());
        aParameters.Add("shipId", shipId);
        aParameters.Add("shipTotal", shipAmount);
        aParameters.Add("tax", tax);
        aParameters.Add("cartTotal", orderTotal);

        wsi._Soap.AddCall("PayPalMakePayment", _PlaceOrderCallback, aParameters);
    }

    var _PlaceOrderCallback = function(returnValue)
    {
        _HideNotification();
        /*
        var isSuccessful = true;
        if (returnValue.indexOf("ERROR") > -1)
        {
        _ErrorResponse = returnValue.replace("ERROR:", "");
        isSuccessful = false;
        }
        */
        _PlaceOrderReturnHandel(returnValue);
    }

    this.ErrorResponse = function()
    {
        return _ErrorResponse;
    }
}

Checkout.PayPal = new Safemart.PayPalBase();
Checkout.PayPalOrder = false;

/// Extend the base class to handle PayPal orders with the cart.
Checkout.PayPal.OrderConfirmed = function()
{
    if (Checkout.PayPal.ValidShipping().toLowerCase() == "false")
    {
        Checkout.PayPal.PlaceOrder(Checkout.PayPal.PlaceOrderReturn, Checkout.Customer.Ship.Type, Checkout.Customer.Ship.Cost, Checkout.Cart.Tax, Checkout.Cart.Total);
    }
    else
    {
        Checkout.PayPal.PlaceOrder(Checkout.PayPal.PlaceOrderReturn, "", Checkout.Customer.Ship.Cost, Checkout.Cart.Tax, Checkout.Cart.Total);
    }
}

Checkout.PayPal.PlaceOrderReturn = function(returnValue)
{
    /// go to the thank you page

    Checkout.PlaceOrderReturnValue = returnValue;
    Checkout.PlaceOrderReturn2()
}

/// Create eBillMe Constructor
Safemart.eBillme = function()
{
    var _Enabled = true;
    var _PreAuthReturn = "";
    var _Preauthrefid = "";
    var _Acceptancepageurl = "";
    var _Authstatus = "";
    var _ConfirmationPageUrl = "";
    var _OrderNumber = "";
    var _AccountNumber = "";

    this.Enabled = function()
    {
        return _Enabled;
    }

    this.Enable = function(enable)
    {
        _Enabled = enable;
    }

    this.GetConfirmationPageUrl = function()
    {
        return _ConfirmationPageUrl;
    }

    this.GetAccountNumber = function()
    {
        return _AccountNumber;
    }

    this.GetOrderNumber = function()
    {
        return _OrderNumber;
    }

    var _DisplayTerms = function()
    {
        //alert("display Terms\r" + _Preauthrefid + "\r" + _Acceptancepageurl + "\r" + _Authstatus);

        if (document.getElementById("eBillmePanel") == null)
        {
            var eBillmePanel = document.createElement("div");
            document.body.appendChild(eBillmePanel);
            eBillmePanel.setAttribute('id', "eBillmePanel");
            eBillmePanel.setAttribute('visibility', 'hidden');

            //<div class="hd" id="eBillCaption" ></div>
            YAHOO.example.container.eBillmePanel = new YAHOO.widget.Panel("eBillmePanel",
			     { fixedcenter: true,
			         visible: false,
			         width: "820px",
			         height: "620px",
			         zIndex: 1000,
			         close: false,
			         modal: true,
			         effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: .5 }
			     });
            YAHOO.example.container.eBillmePanel.render();
        }

        var eBillDiv = document.getElementById("eBillmePanel")
        eBillDiv.innerHTML = '<div class="bd" style="background-color:white;"><iframe id="acceptance" src="' + _Acceptancepageurl + '&next=https://www.safemart.com/checkout/ebillmenext.htm&back=https://www.safemart.com/checkout/ebillmeback.htm&merchant=safemart" width="800px" height="600px" frameborder="0" ></iframe></div>';
        YAHOO.example.container.eBillmePanel.show();

    }

    var _CloseTerms = function()
    {
        YAHOO.example.container.eBillmePanel.hide();
    }
    this.CloseTerms = function()
    {
        _CloseTerms();
    }

    this.PreAuthorizeReturn = function(returnValue)
    {

        //_PreAuthReturn = getDomAdapter().parseXml(returnValue);
        if ('undefined' != typeof ActiveXObject)
        {
            // _XmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            _PreAuthReturn = new ActiveXObject("Microsoft.XMLDOM");
            _PreAuthReturn.loadXML(returnValue);

        }
        else
        {
            _PreAuthReturn = getDomAdapter().parseXml(returnValue);
        }
        //alert(_PreAuthReturn.xml);
        //alert(_PreAuthReturn.getElementsByTagName("preauthrefid")[0].firstChild.nodeValue);
        //alert(_PreAuthReturn.getElementsByTagName("acceptancepageurl")[0].firstChild.nodeValue);
        //alert(_PreAuthReturn.getElementsByTagName("authstatus")[0].firstChild.nodeValue);

        /*
        _Preauthrefid = _PreAuthReturn.childNodes[0].childNodes[0].firstChild.nodeValue;
        _Acceptancepageurl = _PreAuthReturn.childNodes[0].childNodes[1].firstChild.nodeValue;
        _Authstatus = _PreAuthReturn.childNodes[0].childNodes[2].childNodes[0].firstChild.nodeValue;
        */
        _Preauthrefid = _PreAuthReturn.getElementsByTagName("preauthrefid")[0].firstChild.nodeValue;
        _Acceptancepageurl = _PreAuthReturn.getElementsByTagName("acceptancepageurl")[0].firstChild.nodeValue
        _Authstatus = _PreAuthReturn.getElementsByTagName("authstatus")[0].firstChild.nodeValue;
        //alert("preauthorder() return authorization status: " + _Authstatus + "\r\n\r\npreauthorder() response:\r\n" + returnValue);                
        if (_Authstatus == "WAIT")
        {
            _DisplayTerms();
        }
        else
        {
            alert("Sorry, you have not been approved to use the eBillme option. Please select another payment option");
        }
    }

    this.Authorize = function(returnHandler)
    {
        var aParameters = new wsi._Parameters();
        aParameters.Add("preauthrefid", _Preauthrefid);

        wsi._Soap.AddCall("Authorize_eBillme", returnHandler, aParameters);

    }

    this.AuthorizeReturn = function(returnValue)
    {
        //var AuthReturn = getDomAdapter().parseXml(returnValue);


        if ('undefined' != typeof ActiveXObject)
        {
            // _XmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            var AuthReturn = new ActiveXObject("Microsoft.XMLDOM");
            AuthReturn.loadXML(returnValue);

        }
        else
        {
            var AuthReturn = getDomAdapter().parseXml(returnValue);
        }

        _ConfirmationPageUrl = AuthReturn.getElementsByTagName("confirmationpageurl")[0].firstChild.nodeValue;
        _OrderNumber = AuthReturn.getElementsByTagName("ordernumber")[0].firstChild.nodeValue;
        _AccountNumber = AuthReturn.getElementsByTagName("accountnumber")[0].firstChild.nodeValue;

        _CloseTerms();
        //alert(returnValue);
        Checkout.PlaceOrder();
    }

}


Checkout.eBillme = new Safemart.eBillme();


/// Create Cart Object
Checkout.Cart = new Object();
Checkout.Cart.Name = "";
Checkout.OrderError = false;
Checkout.Cart.EmptyText = "Your Cart is currently empty.";
Checkout.Cart.IsEmpty = true;
Checkout.Cart.Weight = 0;
Checkout.Cart.NoFreeShipWeight = 0;
Checkout.Cart.FlatRateShip = 0;
Checkout.Cart.NoShipping = 1;
Checkout.Cart.AdditionalComments = "";
/// Default is 1 - most items will ship in one package.
/// Items that do not qualify for free shipping usually:
///  - weight more
///  - Ship seperatly
/// Therefore, the PieceCount will be incremented for
/// each item that does not qualify for free shipping.
Checkout.Cart.PieceCount = 0;
Checkout.Cart.SubTotal = 0;
Checkout.Cart.Total = 0;
Checkout.Cart.Qty = 0;
Checkout.Cart.Tax = 0;
Checkout.Cart.PromotionCode = "";
Checkout.Cart.Discount = "";
Checkout.Cart.DiscountValue = 0;
Checkout.Cart.DiscountType = "";
Checkout.Cart.Raw = "";
Checkout.Cart.Mode = "Server"; /// Cookie based cart in incomplete. Client side is finish, server side has not been started.
Checkout.Cart.ContainsSmartMoneyPackage = false;
Checkout.Cart.MonitoringServiceType = "";
Checkout.Cart.StandardMonitoring = false;
Checkout.Cart.InteractiveMonitoring = false;
Checkout.Cart.PreprogrammingIncluded = false;
Checkout.Cart.GsmModuleIncluded = false;
Checkout.Cart.VoipModuleInclude = false;

Checkout.TaxRateKs = 6.3;
Checkout.TaxRateIl = 9.5;

Checkout.Init = function()
{
    if (document.getElementById("CheckoutPage") != null)
    {
        /*
        var QueryString = new Safemart.QueryString();
        var PayPalReturn = QueryString.Find("paypalreturn");

        if (PayPalReturn != null && PayPalReturn == "success")
        {
        Checkout.PayPal.GetDetails(Checkout.Load);
        }
        else
        {
        Checkout.Load();
        }
        */


        /// Auto-Load
        Checkout.Load();
    }
}

Checkout.Load = function(entry)
{
    if (typeof (entry) == "undefined") entry = "";
    /*
    /// reset all input fields
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)
    {
    if (inputs[i].type.toLowerCase() != "button")
    {
    inputs[i].value = inputs[i].getAttribute("defaultvalue")

            if (inputs[i].type.toLowerCase() == "radio" && inputs[i].getAttribute("defaultchecked") == 'true')
    {
    inputs[i].checked = true;
    }
    }
    }

    /// reset all Selects
    var inputs = document.getElementsByTagName("select");
    for (var i = 0; i < inputs.length; i++)
    {
    if (inputs[i].getAttribute("defaultvalue") == "")
    {
    inputs[i].value = "";

        }
    else
    {
    inputs[i].value = inputs[i].getAttribute("defaultvalue");
    }
    }
    */

    var QueryString = new Safemart.QueryString();
    var Referrer = QueryString.Find("referrer");

    if (gaCookies != null)
    {
        var gac = new gaCookies();
        var CampaignContent = gac.getCampaignContent();
        var CampaignTerm = gac.getCampaignTerm();

        if (CampaignContent != null && CampaignContent.length > 0)
        {
            Checkout.Customer.LeadSource = CampaignContent;
        }

        if (CampaignTerm != null && CampaignTerm.length > 0)
        {
            Checkout.Customer.CampaignKeyword = CampaignTerm;
        }

    }

    if (Referrer != null && Referrer.toLowerCase() == "security-advisor")
    {
        //Checkout.Customer.LeadSource = "26176";
        Checkout.Customer.OpportunityType = "RMR - Security Advisor"
    }

    var uiPayPalBtn = document.getElementById("uiPayPalBtn");
    var uiPaypalOr = document.getElementById("uiPaypalOr");

    if (Checkout.PayPal.Enabled())
    {
        if (uiPayPalBtn != null) uiPayPalBtn.style.display = "block";
        if (uiPaypalOr != null) uiPaypalOr.style.display = "block";
    }
    else
    {
        if (uiPayPalBtn != null) uiPayPalBtn.style.display = "none";
        if (uiPaypalOr != null) uiPaypalOr.style.display = "none";
    }

    var QueryString = new Safemart.QueryString();
    var PayPalReturn = QueryString.Find("paypalreturn");
    var CouponCode = QueryString.Find("cp");
    var Comments = wsi._Cookie.CartComments();

    if (CouponCode == null || CouponCode == "")
    {
        CouponCrumb = wsi._Cookie.GetCrumb("cp");
        if (CouponCrumb != null)
        {
            CouponCode = CouponCrumb;
        }
    }

    if (CouponCode != null)
    {
        wsi._Cookie.SaveCrumb("cp", CouponCode);
        Checkout.Cart.PromotionCode = CouponCode;
        Checkout.Cart.ApplyCoupon();
    }

    if (Comments != "")
    {
        Checkout.Cart.AdditionalComments = Comments;
    }

    if (Checkout.PayPal.Enabled() && PayPalReturn != null && PayPalReturn == "success")
    {
        Checkout.PayPalOrder = true;
        //Checkout.PayPal.GetDetails(Checkout.PayPal.GetDetailsReturnHandler);
        Checkout.PayPal.GetDetails(Checkout.GetPayPalDetailReturn);
    }
    else
    {
        Checkout.InitializeUI(entry);
    }


    /// Set Progress graphics.


    //Checkout.HideAllSteps()
    //Checkout.ShowStep("stepPayment");
  
}

Checkout.InitializeUI = function(entry)
{
    if (Checkout.Cart.NoShipping)
    {
        /// the shipping address step will be skipped, don't set defaults.
    }
    else
    {
        /// Set default values 
        Checkout.Customer.Ship.State = "AL";
        Checkout.Customer.Ship.StateDomestic = "AL";
        Checkout.Customer.Ship.Country = "US";
        Checkout.Customer.Ship.CountryInternational = "US";

    }

    Checkout.Customer.Bill.State = "AL";
    Checkout.Customer.Bill.StateDomestic = "AL";
    Checkout.Customer.Bill.Country = "US";
    Checkout.Customer.Bill.CountryInternational = "US";
    
    if (entry != "")
    {
        Checkout.HideSubstep("substepChooseCheckout");
        Checkout.ShowSubstep("substepConfidence");


        if (document.getElementById("sidebar-Caption") != null)
        {
            document.getElementById("sidebar-Caption").innerHTML = "Buy with Confidence:";
        }
    }

    if (entry == "PayPalConfirmOrder")
    {

        Checkout.Customer.Ship.AddressLine1 = Checkout.PayPal.Address1();
        Checkout.Customer.Ship.AddressLine2 = Checkout.PayPal.Address2();
        Checkout.Customer.Ship.City = Checkout.PayPal.City();
        Checkout.Customer.Ship.State = Checkout.PayPal.State();
        Checkout.Customer.Ship.Zip = Checkout.PayPal.Zip();
        Checkout.Customer.Ship.Country = Checkout.PayPal.Country();


        if (Checkout.PayPal.ValidShipping().toLowerCase() == "false")
        {

            Checkout.Customer.Ship.GetMethods();

            document.getElementById("PayPalShippingMsg").style.display = "block";
            document.getElementById("uiShippingPrevBtn").style.display = "none";
            Checkout.ShowStep("stepShippingOptions");
        }
        else
        {
            Checkout.Customer.Ship.Cost = Checkout.RoundMoney(Checkout.PayPal.ShipTotal());
            Checkout.ShowStep("stepPayPalConfirmation");
        }
        Checkout.SetTotals();
    }
    else if (entry == "ProceedWithCheckout")
    {
        //Checkout.ShowStep("stepAddress");
        Checkout.NextStep();
    }
    else
    {/// Default entry
        Checkout.ActivateStep("stepCart");
        //Checkout.ActivateStep("stepAddress");


        Checkout.ShowSubstep("substepChooseCheckout");


        /// Track login for Google Analytics
        Checkout.Google.TrackSubPage(0);

        Checkout.SetProgress();


    }

    if (Checkout.Cart.NoShipping)
    {
        /// Don't let the user go to the shipping address step.
        document.getElementById("uiBillingOptionsPrevBtn").style.display = "none";
        document.getElementById("uiBillLogin").style.display = ""; /// return to default
        document.getElementById("uiBIllingEmail").style.display = ""; /// retunr to default

    }

    if (Checkout.ShowSidebar)
    {
        Checkout.ShowSubstep("sidebar");
    }

    Checkout.ShowSubstep("uiTotalBox");
    Checkout.ShowSubstep("CartRef");


}

Checkout.GetPayPalDetailReturn = function(successful)
{
    if (successful)
    {
        Checkout.InitializeUI("PayPalConfirmOrder");
    }
    else
    {
        Checkout.InitializeUI("");
        alert(Checkout.PayPal.ErrorResponse());
    }

}

//document.body.onload = Checkout.onLoad;



Checkout._NewCard = function()
{
    var Card = new Object();
    Card.InternalId = "";
    Card.Default = false;
    Card.Type = "";
    Card.NameOnCard = "";
    Card.Number = "";
    Card.Expiration = "";

    return Card;
}

Checkout.Customer.ShowLogin = function()
{
    //
    document.getElementById("CheckoutNotificationCaption").innerHTML = "Enter Account Login";
    document.getElementById("CheckoutNotificationMessage").innerHTML = document.getElementById("LoginOverlay").innerHTML.replace("_#Msg#_", '<span id="LoginMessage" style="color:red"></span>');
    YAHOO.example.container.panel1.show();

}

Checkout.Customer.HideLogin = function()
{
    YAHOO.example.container.panel1.hide(); /// close notificaion window.
}

Checkout.Customer.Login = function()
{
    //YAHOO.example.container.panel1.hide(); /// close the login overlay.

    if (Checkout.Customer.Email.length > 0 && Checkout.Customer.Password.length > 0)
    {
        //document.getElementById("LoginMessage").innerHTML = "Login in progress...";
        //document.getElementById("LoginMessage").style.color = "Blue";

        SessionID = Safemart.GetSession();

        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionID", SessionID);
        aParameters.Add("email", Checkout.Customer.Email);
        aParameters.Add("password", Checkout.Customer.Password);

        document.getElementById("CheckoutNotificationCaption").innerHTML = "Customer Login";
        // SHILL 11/17/08 document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Login in progress...</center><br /><br />";
        document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Processing Login<br /><img src='/img/images/progress.gif' alt=''></center><br /><br />";

        YAHOO.example.container.panel1.show();

        wsi._Soap.AddCall("CustomerLogin", Checkout.Customer.LoginReturn, aParameters);
    }
    else if (Checkout.Customer.Email.length == 0)
    {
        //alert("An email address is required for login");
        document.getElementById("LoginMessage").innerHTML = "An email address is required for login";
        //document.getElementById("LoginMessage").style.color = "Red";
    }
    else
    {
        //alert("A password is required for login");
        document.getElementById("LoginMessage").innerHTML = "A password is required for login";
        //document.getElementById("LoginMessage").style.color = "Red";
    }

    //<div class="hd" id="CheckoutNotificationCaption" ></div>
    //<div class="bd"  id="CheckoutNotificationMessage" ><div>



}

Checkout.Customer.LoginReturn = function(returnData)
{
    if (returnData.substring(0, 5) == "error")
    {
        Checkout.Customer.ShowLogin();
        document.getElementById("LoginMessage").innerHTML = returnData.substring(7);
        document.getElementById("LoginMessage").style.color = "Red";

    }
    else
    {
        Checkout.Customer.HideLogin();

        //document.getElementById("substepCart").style.display = "none";
        //Checkout.ShowStep(Checkout.Steps[1]);

        var Rows = returnData.split("||");

        for (var iRow = 0; iRow < Rows.length; iRow++)
        {
            var Fields = Rows[iRow].split("|");

            if (Rows[iRow].indexOf("Customer|") > -1)
            {
                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {
                        case "InternalId":
                            Checkout.Customer.InternalID(Values[1]);
                            break;

                        case "FirstName":
                            Checkout.Customer.Ship.FirstName = Values[1];
                            break;

                        case "LastName":
                            Checkout.Customer.Ship.LastName = Values[1];
                            break;

                        case "CompanyName":
                            Checkout.Customer.Ship.Company = Values[1];
                            break;

                        case "Email":
                            Checkout.Customer.Email = Values[1];
                            break;
                    }
                }
            }

            if (Rows[iRow].indexOf("isShip=True") > 0)
            {
                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {

                        case "InternalId":
                            Checkout.Customer.Ship.InternalId = Values[1];
                            break;

                        case "Addressee":
                            Checkout.Customer.Ship.Company = Values[1];
                            break;

                        case "Attention":
                            // Override the Customer First and Last Name
                            var l_nDelimiter = Values[1].indexOf(' ');
                            var First = Values[1].substring(0, l_nDelimiter)
                            var Last = Values[1].substring(l_nDelimiter + 1, Values[1].length);

                            Checkout.Customer.Ship.FirstName = First;
                            Checkout.Customer.Ship.LastName = Last;
                            break;

                        case "Address1":
                            Checkout.Customer.Ship.AddressLine1 = Values[1];
                            break;

                        case "Address2":
                            Checkout.Customer.Ship.AddressLine2 = Values[1];
                            break;

                        case "City":
                            Checkout.Customer.Ship.City = Values[1];
                            break;

                        case "State":
                            Checkout.Customer.Ship.State = Values[1];
                            break;

                        case "Zip":
                            Checkout.Customer.Ship.Zip = Values[1];
                            break;

                        case "Country":
                            Checkout.Customer.Ship.Country = Values[1];
                            break;

                        case "Phone":
                            Checkout.Customer.Ship.Phone = Values[1];
                            break;
                    }
                }
            }

            if (Rows[iRow].indexOf("isBill=True") > 0 && Rows[iRow].indexOf("isShip=True") > 0)
            {
                Checkout.Customer.Bill.SameAsShip = true;
            }

            if (Rows[iRow].indexOf("isBill=True") > 0)
            {
                Checkout.Customer.Bill.SameAsShip = false;

                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {
                        case "InternalId":
                            Checkout.Customer.Bill.InternalId = Values[1];
                            break;

                        case "Addressee":
                            Checkout.Customer.Bill.Company = Values[1]
                            break;

                        case "Attention":
                            var l_nDelimiter = Values[1].indexOf(' ');
                            var First = Values[1].substring(0, l_nDelimiter)
                            var Last = Values[1].substring(l_nDelimiter + 1, Values[1].length);

                            Checkout.Customer.Bill.FirstName = First;
                            Checkout.Customer.Bill.LastName = Last;
                            break;

                        case "Address1":
                            Checkout.Customer.Bill.AddressLine1 = Values[1];
                            break;

                        case "Address2":
                            Checkout.Customer.Bill.AddressLine2 = Values[1];
                            break;

                        case "City":
                            Checkout.Customer.Bill.City = Values[1];
                            break;

                        case "State":
                            Checkout.Customer.Bill.State = Values[1];
                            break;

                        case "Zip":
                            Checkout.Customer.Bill.Zip = Values[1];
                            break;

                        case "Country":
                            Checkout.Customer.Bill.Country = Values[1];
                            break;

                        case "Phone":
                            Checkout.Customer.Bill.Phone = Values[1];
                            break;
                    }
                }
            }

            if (Rows[iRow].indexOf("Card|") > -1)
            {
                Checkout.Customer.CreditCard.CardsOnFile[Checkout.Customer.CreditCard.CardsOnFile.length] = Checkout._NewCard();
                Card = Checkout.Customer.CreditCard.CardsOnFile[Checkout.Customer.CreditCard.CardsOnFile.length - 1];

                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {
                        case "InternalId":
                            Card.InternalId = Values[1];
                            break;

                        case "isDefault":
                            if (Values[1] == "true")
                            {
                                Card.Default = true;
                            }
                            break;

                        case "Type":
                            Card.Type = Values[1];
                            break;

                        case "NameOnCard":
                            Card.NameOnCard = Values[1];
                            break;

                        case "Number":
                            Card.Number = Values[1];
                            break;

                        case "Expiration":
                            Card.Expiration = Values[1];
                            break;
                    }
                }
            }
        }


        // Update the Shipping Fields
        document.getElementById("txtShipFirstName").value = Checkout.Customer.Ship.FirstName;
        document.getElementById("txtShipLastName").value = Checkout.Customer.Ship.LastName;
        document.getElementById("txtShipCompanyName").value = Checkout.Customer.Ship.Company;
        document.getElementById("txtCustomerEmail").value = Checkout.Customer.Email;
        document.getElementById("txtCustomerBillEmail").value = Checkout.Customer.Email;
        document.getElementById("txtShipAddress1").value = Checkout.Customer.Ship.AddressLine1;
        document.getElementById("txtShipAddress2").value = Checkout.Customer.Ship.AddressLine2;
        document.getElementById("txtShipCity").value = Checkout.Customer.Ship.City;
        if (Checkout.Customer.Ship.Country == "US")
        {
            Checkout.Customer.Ship.StateDomestic = Checkout.Customer.Ship.State;
            //document.getElementById("optShipStateProvince").value = Checkout.Customer.Ship.State;
        }
        else if (Checkout.Customer.Ship.Country == "CA")
        {
            Checkout.Customer.Ship.StateCanada = Checkout.Customer.Ship.State;
            //document.getElementById("optShipStateProvince_Canada").value = Checkout.Customer.Ship.State;
        }
        else
        {
            Checkout.Customer.Ship.StateInternational = Checkout.Customer.Ship.State;
            //document.getElementById("txtShipStateProvince").value = Checkout.Customer.Ship.State;
        }
        Checkout.SetStateField("Ship");

        document.getElementById("txtShipZipPostalCode").value = Checkout.Customer.Ship.Zip;
        document.getElementById("optShipCountryId").value = Checkout.Customer.Ship.Country;
        if (Checkout.Customer.Ship.Country != "US")
        {
            Checkout.Customer.Ship.CountryInternational = Checkout.Customer.Ship.Country;
            Checkout.ToggleCountryField("Ship");
        }

        if (Checkout.Customer.Ship.Phone.length > 0)
        {
            ClearInputExample(document.getElementById("txtShipPhoneNumber"))

            var PhoneNumber = Checkout.Customer.Ship.Phone;
            PhoneNumber = PhoneNumber.replace("-", " ").replace("(", "").replace(")", "");
            var PhoneArray = PhoneNumber.split(" ");

            document.getElementById("txtShipPhoneArea").value = PhoneArray[0];
            document.getElementById("txtShipPhonePrefix").value = PhoneArray[1];
            document.getElementById("txtShipPhoneSuffix").value = PhoneArray[2];



        }
        document.getElementById("txtShipPhoneNumber").value = Checkout.Customer.Ship.Phone;

        // Update the Bill to Fields
        if (!Checkout.Customer.Bill.SameAsShip)
        {
            document.getElementById("txtBillSameAsShipNo").click();
            document.getElementById("txtBillFirstName").value = Checkout.Customer.Bill.FirstName;
            document.getElementById("txtBillLastName").value = Checkout.Customer.Bill.LastName;
            document.getElementById("txtBillCompanyName").value = Checkout.Customer.Bill.Company;
            document.getElementById("txtBillAddress1").value = Checkout.Customer.Bill.AddressLine1;
            document.getElementById("txtBillAddress2").value = Checkout.Customer.Bill.AddressLine2;
            document.getElementById("txtBillCity").value = Checkout.Customer.Bill.City;
            if (Checkout.Customer.Bill.Country == "US")
            {
                Checkout.Customer.Bill.StateDomestic = Checkout.Customer.Bill.State;
                //document.getElementById("optBillStateProvince").value = Checkout.Customer.Bill.State;
            }
            else if (Checkout.Customer.Bill.Country == "CA")
            {
                Checkout.Customer.Bill.StateCanada = Checkout.Customer.Bill.State;
                //document.getElementById("optBillStateProvince_Canada").value = Checkout.Customer.Bill.State; 
            }
            else
            {
                Checkout.Customer.Bill.StateInternational = Checkout.Customer.Bill.State;
                //document.getElementById("txtBillStateProvince").value = Checkout.Customer.Bill.State;
            }
            Checkout.SetStateField("Bill");

            document.getElementById("txtBillZipPostalCode").value = Checkout.Customer.Bill.Zip;
            document.getElementById("optBillCountryId").value = Checkout.Customer.Bill.Country;
            if (Checkout.Customer.Bill.Country != "_unitedStates")
            {
                Checkout.Customer.Bill.CountryInternational = Checkout.Customer.Bill.Country;
                Checkout.ToggleCountryField("Bill");
            }

            if (Checkout.Customer.Bill.Phone.length > 0)
            {
                ClearInputExample(document.getElementById("txtBillPhoneNumber"))

                var PhoneNumber = Checkout.Customer.Bill.Phone;
                PhoneNumber = PhoneNumber.replace("-", " ").replace("(", "").replace(")", "");
                var PhoneArray = PhoneNumber.split(" ");

                document.getElementById("txtBillPhoneArea").value = PhoneArray[0];
                document.getElementById("txtBillPhonePrefix").value = PhoneArray[1];
                document.getElementById("txtBillPhoneSuffix").value = PhoneArray[2];
            }
            document.getElementById("txtBillPhoneNumber").value = Checkout.Customer.Bill.Phone;

        }
    }
}

Checkout.Customer.Ship.GetMethods = function()
{

    var aParameters = new wsi._Parameters();
    //aParameters.Add("firstName",Checkout.Customer.Ship.FirstName);
    //aParameters.Add("lastName",Checkout.Customer.Ship.LastName);
    //aParameters.Add("company",Checkout.Customer.Ship.Company);
    aParameters.Add("addressLine1", Checkout.Customer.Ship.AddressLine1);
    aParameters.Add("addressLine2", Checkout.Customer.Ship.AddressLine2);
    aParameters.Add("city", Checkout.Customer.Ship.City);
    aParameters.Add("state", Checkout.Customer.Ship.State);
    aParameters.Add("zip", Checkout.Customer.Ship.Zip);
    aParameters.Add("country", Checkout.Customer.Ship.Country);
    //aParameters.Add("phone",Checkout.Customer.Ship.Phone);
    aParameters.Add("weight", Checkout.Cart.Weight);
    aParameters.Add("noFreeShipWeight", Checkout.Cart.NoFreeShipWeight);
    aParameters.Add("pieceCount", Checkout.Cart.PieceCount);
    //alert("weight "+Checkout.Cart.Weight);
    wsi._Soap.AddCall("GetShippingMethods", Checkout.Customer.Ship.MethodsReturn, aParameters);
}

Checkout.Customer.Ship.MethodsReturn = function(returnData)
{
    //alert(returnData);
    Checkout.Customer.Ship.Raw = returnData;

    /// reset Ship properties
    Checkout.Customer.Ship.Cost = 0;
    // SHILL 09-22-2008
    // Don't clear the Shipping Type. 
    // If the customer changes item qty the shipping
    //  is re-caculated without changing the type
    //    Checkout.Customer.Ship.Type = "";

    document.getElementById("ShipMethodMessage").innerHTML = "";

    if (returnData.substring(0, 5) == "error")
    {
        alert(returnData.substring(7));
    }
    else
    {
        var aShipMethods = returnData.split("||")

        var ShipTable = "";
        ShipTable += '<table border="0" width="500px" cellspacing="0" cellpadding="4px">';
        if (Checkout.Cart.NoFreeShipWeight > 0 || Checkout.Cart.FlatRateShip > 0)
        {
            ShipTable += '<tr>' +
                            '<td colspan="2" style="text-align:right;">' +
                                 "<span style='position:relative;'>" +
                                    "<span id='NoFreeShipOverlayLink' class='CheckoutLink' onmouseover='Checkout.ShowNoFreeShippingOverlay();' onmouseout='Checkout.HideNoFreeShippingOverlay();'>" +
                                        "Why don't I see a free shipping option?" +
                                    "</span>" +
                                "</span>" +
                            '</td>' +
                            '</tr>'
        }

        ShipTable += '<tr>' +
                        '<td style="border-bottom:solid 1px black;">' +
                        '<b>Shipping Method</b>' +
                        '</td>' +
                        '<td style="border-bottom:solid 1px black;">' +
                        '<b>Price</b>' +
                        '</td>' +
                        '</tr>';

        /// reset Ship Cost    
        Checkout.Customer.Ship.Cost = 0;

        var FreeShippingAt = 199.00;

        /// Default cost for Premium and Ground Shipping
        var PremiumShipCost = 11.75;
        var GroundShipCost = 6.95;

        if (Checkout.Cart.FlatRateShip > 0 || Checkout.Cart.NoFreeShipWeight > 0)
        {
            var NoFreeShipCost = 0;

            if (Checkout.Cart.NoFreeShipWeight > 0)
            {
                var NoFreeRowNum = aShipMethods.findAt("NOFREE_FEDEX_GROUND", 0, "contains");

                if (NoFreeRowNum > -1)
                {
                    NoFreeShipCost = parseFloat(aShipMethods[NoFreeRowNum].split("|")[1]);
                }
            }
            //alert(NoFreeShipCost);
            GroundShipCost = parseFloat(Checkout.Cart.FlatRateShip) + NoFreeShipCost;
        }

        /// California residents get upgraded to 2day air for the cost of ground.
        if (Checkout.Cart.SubTotal >= 100.00)
        {
            Cali2dayAirCost = 0;
        }
        else
        {
            var Cali2dayAirCost = GroundShipCost;
        }

        if (Checkout.Customer.Ship.Type == "2926" || Checkout.Customer.Ship.Type == "1785")
        {
            /// If the subtotal is greater that $99 the order qualifies for free shipping
            /// and all items qualify for free shipping
            /// and all items are not Flat rate shipping items
            if (Checkout.Cart.SubTotal >= FreeShippingAt && Checkout.Cart.NoFreeShipWeight == 0 && Checkout.Cart.FlatRateShip == 0)
            {
                var ShipType = "2926";
            }
            else
            {
                var ShipType = "1785";
            }
        }
        else
        {
            var ShipType = Checkout.Customer.Ship.Type;
        }

        if (Checkout.Customer.Ship.Country == "US")
        {

         var ContinentalUs = false;
         if (
             Checkout.Customer.Ship.State != "AK" /// Alaska
             && Checkout.Customer.Ship.State != "HI" /// Hawaii
             && Checkout.Customer.Ship.State != "AS" /// American Samoa
             && Checkout.Customer.Ship.State != "FM" /// Federated States of Micronesia
             && Checkout.Customer.Ship.State != "GU" /// Guam
             && Checkout.Customer.Ship.State != "MH" /// Marshall Islands
             && Checkout.Customer.Ship.State != "MP" ///Northern Mariana Islands
             && Checkout.Customer.Ship.State != "PW"  /// Palau
             && Checkout.Customer.Ship.State != "PR" /// Puerto Rico
             && Checkout.Customer.Ship.State != "VI" /// Virgin Islands
         )
         {
             ContinentalUs = true;
         }
         
            // Only the Continental US
            //if (Checkout.Customer.Ship.State != "AK" && Checkout.Customer.Ship.State != "HI")
            if (ContinentalUs)
            {


                if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == "2925")
                {/// Apply free shipping - customer entered a coupon
                    PremiumShipCost = 0;
                }

                if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == "1785")
                {/// Apply free shipping - customer entered a coupon
                    GroundShipCost = 0;
                }


                if (ShipType == "2925")
                {
                    Checkout.Customer.Ship.Cost = PremiumShipCost;
                }
                else if (ShipType == "2926")
                {
                    Checkout.Customer.Ship.Cost = 0;
                }
                else if (ShipType == "1785")
                {
                    Checkout.Customer.Ship.Cost = GroundShipCost;
                }

                /// If the cart contains items that do not qualify for free shipping
                /// or if the cart contains flat rate shipping items
                ///     - do not include the option for premium shipping
                ///     - do not include the option for free shipping
                if (Checkout.Cart.NoFreeShipWeight == 0 && Checkout.Cart.FlatRateShip == 0)
                {
                    ShipTable += '<tr>' +
                                '<td>' +
                                '       <input id="ShipMethod_Premium" type="radio" name="ShippingOption" value="2925|' + PremiumShipCost + '" ' + (ShipType == '2925' || ShipType.length == 0 ? 'checked="checked"' : '') + ' />Premium - Delivered in 3 days' +
                                '    </td>' +
                                '    <td>' +
                                '        ' + Checkout.ToMoney(PremiumShipCost) +
                                '    </td>' +
                                '</tr>';

                    ShipTable += '<tr>' +
                                '    <td>' +
                                '        <input id="ShipMethod_Ground" type="radio" name="ShippingOption" ' + (ShipType == '2926' || ShipType == '1785' ? 'checked="checked"' : '') + ' value="' + (Checkout.Cart.SubTotal >= FreeShippingAt ? "2926|0.00" : "1785|" + GroundShipCost) + '" />' +
                                         (Checkout.Cart.SubTotal >= FreeShippingAt ? "Free Shipping - " : "") + "Ground Service" +
                                '    </td>' +
                                '    <td>' +
                                        (Checkout.Cart.SubTotal >= FreeShippingAt ? "$0.00" : Checkout.ToMoney(GroundShipCost)) +
                                '    </td>' +
                                '</tr>';
                }
                else
                {
                    var ShipLabel = "";
                    if (Checkout.Cart.FlatRateShip > 0)
                    {
                        ShipLabel = "Flat Rate Shipping";
                    }
                    else
                    {
                        ShipLabel = "Ground Service";
                    }

                    ShipTable += '<tr>' +
                                '    <td>' +
                                '        <input id="ShipMethod_Ground" type="radio" name="ShippingOption" ' + (ShipType == '1785' ? 'checked="checked"' : '') + ' value="1785|' + GroundShipCost + '" />' +
                                         ShipLabel +
                                '    </td>' +
                                '    <td>' +
                                        Checkout.ToMoney(GroundShipCost) +
                                '    </td>' +
                                '</tr>';
                }

            }

            // All 50 States
            var iFedExStdOvernight = aShipMethods.findAt("STANDARD_OVERNIGHT|", 0, "contains");
            var iFedExPriOvernight = aShipMethods.findAt("PRIORITY_OVERNIGHT|", 0, "contains");
            var iFedExTwoDay = aShipMethods.findAt("FEDEX_2_DAY|", 0, "contains");
            //alert(iFedExTwoDay);
            if (iFedExTwoDay > -1)
            {
                /// Default Cost for FedeEx 2day air
                var ShipCost = parseFloat(aShipMethods[iFedExTwoDay].split("|")[1]);
                var TwoDayAirName = "FedEx 2-Day Air";

                /// California gets Free upgrade - 2nd day air for the cost of ground
                /* Promotion over
                if (Checkout.Cart.FlatRateShip == 0 && Checkout.Customer.Ship.Country == "US" && Checkout.Customer.Ship.State == "CA")
                {
                    var ShipCost = Cali2dayAirCost;
                    var TwoDayAirName = "FedEx 2-Day Air - <span style='color:red;'>California Special Only</span>";
                }
                */
                
                if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == "9")
                {/// Apply free shipping - customer entered a coupon
                    ShipCost = 0;
                }

                if (ShipType == "9")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '    <td>' +
                                '        <input id="ShipMethod_FEDEX_2_DAY" type="radio" name="ShippingOption" ' + (ShipType == '9' ? 'checked="checked"' : '') + ' value="9|' + ShipCost + '" />' + TwoDayAirName +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExStdOvernight > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExStdOvernight].split("|")[1]);


                if (ShipType == "1786")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_STANDARD_OVERNIGHT" type="radio" name="ShippingOption" ' + (ShipType == '1786' ? 'checked="checked"' : '') + ' value="1786|' + ShipCost + '" />FedEx Standard Overnight' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExPriOvernight > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExPriOvernight].split("|")[1]);

                if (ShipType == "2923")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_"PRIORITY_OVERNIGHT" type="radio" name="ShippingOption" ' + (ShipType == '2923' ? 'checked="checked"' : '') + '  value="2923|' + ShipCost + '" />FedEx Priority Overnight' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }
        }
        else
        {
            var iFedExEco = aShipMethods.findAt("INTERNATIONAL_ECONOMY|", 0, "contains");
            var iFedExPri = aShipMethods.findAt("INTERNATIONAL_PRIORITY|", 0, "contains");
            var iFedExGrd = -1;

            /// Canadians don't get a ground option
            if (Checkout.Customer.Ship.Country != "CA")
            {
                var iFedExGrd = aShipMethods.findAt("FEDEX_GROUND|", 0, "contains");
            }

            if (iFedExGrd > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExGrd].split("|")[1]);

                if (ShipType == "1785" || ShipType.length == 0)
                {
                    ShipType = "1785"
                    Checkout.Customer.Ship.Type = "1785";

                    Checkout.Customer.Ship.Cost = ShipCost;
                }


                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_FEDEX_GROUND" type="radio" name="ShippingOption" ' + (ShipType == '1785' ? 'checked="checked"' : '') + ' value="1785|' + ShipCost + '" />FedEx Ground' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExEco > -1)
            {

                var ShipCost = parseFloat(aShipMethods[iFedExEco].split("|")[1]);

                /// Canadians pay 50% on the shipping rate
                if (Checkout.Customer.Ship.Country == "CA")
                {
                    ShipCost /= 2;
                }

                if (ShipType == "1787" || (iFedExGrd == -1 && ShipType.length == 0))
                {
                    ShipType = "1787"
                    Checkout.Customer.Ship.Type = "1787";

                    Checkout.Customer.Ship.Cost = ShipCost;
                }


                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_INTERNATIONAL_ECONOMY" type="radio" name="ShippingOption" ' + (ShipType == '1787' ? 'checked="checked"' : '') + ' value="1787|' + ShipCost + '" />International Economy' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExPri > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExPri].split("|")[1]);

                /// Canadians pay 50% on the shipping rate
                if (Checkout.Customer.Ship.Country == "CA")
                {
                    ShipCost /= 2;
                }

                if (ShipType == "2924")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_INTERNATIONAL_PRIORITY" type="radio" name="ShippingOption" ' + (ShipType == '2924' ? 'checked="checked"' : '') + ' value="2924|' + ShipCost + '" />International Priority' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }
        }

        ShipTable += '<tr>' +
                    '   <td colspan="2" style="border-top:solid 1px black;">' +
                    '    &nbsp;</td>' +
                    '</tr>' +
                    '</table>';

        document.getElementById("ShipMethods").innerHTML = ShipTable;
        if (document.getElementsByName("ShippingOption").length > 0)
        {
            //document.getElementsByName("ShippingOption")[0].checked = true;
        }
        else
        {
            document.getElementById("ShipMethods").innerHTML = "<span style='color:red;'>There are no shipping options available for your location. Please use the Previous button to check you shipping address.</span>";
        }

        Checkout.SetTotals();

    }
}



Checkout.Cart.View = function()
{
    if (document.getElementById("CartItemCount") != null && document.getElementById("CartItemCount").innerHTML == "0")
    {
        alert("There are currently no items in your cart.");
    }
    else
    {
        if (document.domain == "quarantine.safemart.com")
        {
            document.location.href = "https://" + document.domain + "/checkout.htm"
        }
        else
        {
            document.location.href = "https://www.safemart.com/checkout.htm"
        }
    }
}

Checkout.Cart.Get = function()
{
    if (Checkout.Cart.Mode == "Server")
    {
        var SessionID = Safemart.GetSession();

        if (SessionID != "")
        {
            var aParameters = new wsi._Parameters();
            aParameters.Add("sessionID", SessionID + Checkout.Cart.Name);
            wsi._Soap.AddCall("GetCart", Checkout.Cart.GetReturn, aParameters);
        }
        else
        {
            Checkout.Cart.GetReturn(null)
        }
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        Checkout.Cart.GetReturn(Checkout.CartProcessor.GetCart());
    }

    wsi.GetIP(Checkout.GetIPReturn);
}

Checkout.GetIPReturn = function(ip)
{
    //alert(ip);

    Checkout.Customer.IP = ip

    ///192.168.253.1 = local.quarantine.safemart.com
    ///192.168.253.10 = local.www.safemart.com
    ///64.6.124.68 = Old Ocusafe Location - Moats building
    ///64.6.124.68 = New Ocusafe Location - Bertrand
    if (ip == "64.6.124.68" || ip == "64.6.124.16" || ip == "139.146.141.27" || ip == "192.168.253.1" || ip == "192.168.253.10")
    {
        Checkout.Customer.InternalIP = true;
        document.getElementById("Internal").style.display = "block";

    }
}

Checkout.Cart.LineItemTemplate = "" +
         "<tr id='_#GroupId#_'>" +
            "<td width='55px' rowspan='2' valign='top' style='padding-top:10px;padding-right:10px;'>" +
                "<img src='_#ImgLocation#_' width='50px' height='50px' />" +
            "</td>" +
            "<td colspan='3' valign='top' style='padding-top:10px'>" +
                "<a href='_#ItemLocation#_'>_#ItemName#_</a>" +
                " &nbsp;" +
                "<span style='position:relative;'>" +
                    "<span id='OptionLink_#GroupId#_' class='CheckoutLink'" +
//" onmouseover='document.getElementById(\"Customizations_#GroupId#_\").style.display = \"block\";'"+
                        " onmouseover='YAHOO.example.container.overlay1.cfg.setProperty(\"context\", [\"OptionLink_#GroupId#_\",\"tl\",\"bl\"]); YAHOO.example.container.overlay1.setBody(document.getElementById(\"Customizations_#GroupId#_\").innerHTML);YAHOO.example.container.overlay1.show()'" +
//" onmouseout='document.getElementById(\"Customizations_#GroupId#_\").style.display = \"none\"' >_#CustomizationLink#_"+
                        " onmouseout='YAHOO.example.container.overlay1.hide()' >_#CustomizationLink#_" +
                    "</span>" +
                    "<div id='Customizations_#GroupId#_' style='display:none;z-index:1000;position:absolute;top:25px;left:-20px;padding:10px;background-color:white;border:solid 1px #c0c0c0;'>_#Customizations#_</div>" +
                "</span>" +
            "</td>" +
         "</tr>" +
         "<tr>" +
            "<td valign='top'>" +
                "<span>item# _#Sku#_</span>" +
            "</td>" +
            "<td valign='top'>" +
                "<input type='text'id='Qty_#GroupId#_' onkeyup='Checkout.ValidateQty(this);' onblur='Checkout.ValidateQty(this,true);' defaultvalue='_#Qty#_' value='_#Qty#_' size='1' maxlength='3' style='height:20px;' />" +
                "&nbsp;Qty" +
                "&nbsp;<span class='CheckoutLink' style='font-size:11px;' onclick='Checkout.Cart.ChangeItemQty(\"_#GroupId#_\", \"Qty_#GroupId#_\");'>Update</span>" +
                "&nbsp;<span class='CheckoutLink' style='font-size:11px;'  onclick='Checkout.Cart.RemoveItem(\"_#GroupId#_\",\"_#NsId#_\")'>Remove</span>" +
            "</td>" +
            "<td align='right' valign='top'>" +
                "<div style='_#PriceStyles#_'>" +
                    "<span id='Price_#GroupId#_'>_#Price#_</span>" +
                    "&nbsp;&nbsp;&nbsp;&nbsp;<span id='Total_#GroupId#_'>_#Total#_</span>" +
                "</div>" +
                "<div style='display:_#DiscountDisplay#_;color:red;'>" +
                    "<span>(discounted)&nbsp&nbsp</span>" +
                    "<span id='DiscountPrice_#GroupId#_'>_#DiscountPrice#_</span>" +
                    "&nbsp;&nbsp;&nbsp;&nbsp;<span id='DiscountTotal_#GroupId#_'>_#DiscountTotal#_</span>" +
                "</div>" +

            "</td>" +
        "</tr>";


Checkout.ItemToRemove = "";
Checkout.ItemToRemoveId = "";

Checkout.Cart.RemoveItem = function(groupId, netsuitId)
{
    Checkout.ItemToRemove = groupId;
    Checkout.ItemToRemoveId = netsuitId;

    var Message = document.getElementById("RemoveCartItemNotification").innerHTML;

    if (Checkout.Cart.Discount.length > 0)
    {
        Message = Message.replace(/PromotionNotice/g, "Removing items may disqualify your coupon. ");
    }
    else
    {
        Message = Message.replace(/PromotionNotice/g, "");
    }
    /// reset the smart money flag.
    /// after the remove, if the cart still contains the Smart Money Package.
    /// the flag will be set to true.
    Checkout.Cart.ContainsSmartMoneyPackage = false;

    /// Clear the Monitoring properties
    Checkout.Cart.MonitoringServiceType = "";
    Checkout.Cart.StandardMonitoring = false;
    Checkout.Cart.InteractiveMonitoring = false;
    Checkout.Cart.PreprogrammingIncluded = false;
    Checkout.Cart.GsmModuleIncluded = false;
    Checkout.Cart.VoipModuleInclude = false;

    /// Reset the eBillme enabled to true
    /// eBillme is disable when the cart contains the Smart Money package.
    Checkout.eBillme.Enable(true);

    document.getElementById("CheckoutNotificationCaption").innerHTML = "Remove from Cart";
    document.getElementById("CheckoutNotificationMessage").innerHTML = Message;
    YAHOO.example.container.panel1.show();


}

Checkout.RemoveItemConfirmed = function(removeItem)
{
    YAHOO.example.container.panel1.hide();

    if (removeItem)
    {
        groupId = Checkout.ItemToRemove;

        var SessionID = Safemart.GetSession();

        document.getElementById("CartItems").innerHTML = "Removing Item from Cart...";

        if (Checkout.Cart.Mode == "Server")
        {
            if (SessionID != "")
            {
                var aParameters = new wsi._Parameters();
                aParameters.Add("sessionID", SessionID);
                aParameters.Add("groupId", groupId);


                wsi._Soap.AddCall("RemoveFromCart", Checkout.Cart.GetReturn, aParameters);

            }
            else
            {
                Checkout.Cart.GetReturn(null);
            }
        }
        else if (Checkout.Cart.Mode == "Cookie")
        {
            Checkout.Cart.GetReturn(Checkout.CartProcessor.RemoveFromCart(groupId));
        }
        
        Checkout.FetchBack.Abandon(Checkout.ItemToRemoveId);
    }
}

Checkout.Cart.ChangeItemQty = function(groupId, qtyField)
{
    var Qty = document.getElementById(qtyField).value
    document.getElementById("CartItems").innerHTML = "Updating Quantity...";

    if (Checkout.Cart.Mode == "Server")
    {
        var SessionID = Safemart.GetSession();

        if (SessionID != "")
        {
            var aParameters = new wsi._Parameters();
            aParameters.Add("sessionID", SessionID);
            aParameters.Add("groupId", groupId);
            aParameters.Add("qty", Qty);

            wsi._Soap.AddCall("ChangeCartQty", Checkout.Cart.GetReturn, aParameters);

        }
        else
        {
            Checkout.Cart.GetReturn(null);
        }
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        Checkout.Cart.GetReturn(Checkout.CartProcessor.UpdateQty(groupId, Qty));
    }
}

Checkout.Cart.GetViewText = function()
{
    wsi.Cart.GetViewText();
}

Checkout.UseConsultantMsg = false;

Checkout.Cart.GetReturn = function(returnValue)
{

    Checkout.Cart.Raw = returnValue;

    /// both Cart.RemoveItem and Cart.UpdateQty return to this funtion.
    /// call GetViewText to update the cart view in the header
    Checkout.Cart.GetViewText();

    /// reset the weigth and  subtotal
    Checkout.Cart.Weight = 0;
    Checkout.Cart.SubTotal = 0;

    /// Reset No Free Shipping weight
    Checkout.Cart.NoFreeShipWeight = 0;
    Checkout.Cart.PieceCount = 0;

    /// Reset Flat Rate Shipping
    Checkout.Cart.FlatRateShip = 0;

    /// Reset the No Shipping flag
    Checkout.Cart.NoShipping = 1;

    /// Resetn the Show Param
    Checkout.ThankyouPageShowParam = "&show=4";

    if (returnValue == null || returnValue.length == 0)
    {
        document.getElementById("CartItems").innerHTML = Checkout.Cart.EmptyText;
        Checkout.Cart.IsEmpty = true;
    }
    else if (returnValue.substring(0, 5) == "error")
    {
        document.getElementById("CartItems").innerHTML = returnValue;
        Checkout.Cart.IsEmpty = true;
    }
    else
    {
        Checkout.Cart.IsEmpty = false;

        var CartArray = returnValue.split("||");
        //alert(CartArray.join("\r\n\r\n"));        
        var Groups = new Array();
        var GroupMap = new Array();

        for (var iItems = 0; iItems < CartArray.length; ++iItems)
        {
            var ItemProperties = CartArray[iItems].split("|");

            var GroupNumber = Groups.findAt(ItemProperties[0], 0)

            if (GroupNumber == -1)
            {
                Groups[Groups.length] = ItemProperties[0];
                GroupMap[GroupMap.length] = "" + iItems; /// It must be a string
            }
            else
            {
                GroupMap[GroupNumber] += "," + iItems;
            }
        }


        Checkout.CommissionJunctionPixel.ClearItems();
        var ItemListHTML = "";

        //for (var iItems=0; iItems<CartArray.length; ++iItems)
        for (var iGroups = 0; iGroups < Groups.length; iGroups++)
        {

            var ThisGroup = GroupMap[iGroups]
            /*
            //if (GroupMap[iGroups] == 0)
            if (GroupMap[iGroups].indexOf(",") == -1)
            { // split doesn't work if value = 0
            var GroupIds = new Array();
            GroupIds[0] = GroupMap[iGroups];
            }
            else
            {
            var GroupIds = GroupMap[iGroups].split(",");
            }
            */
            var GroupIds = GroupMap[iGroups].split(",");

            var ItemHTML = Checkout.Cart.LineItemTemplate;
            var CustomizationLink = "";
            var CustomizationsHTML = "";
            var UnitPrice = 0;
            var UnitDiscountPrice = 0;
            var TotalPrice = 0;
            var BaseQty = 0;

            /// Clear the FetchBack Purchase List
            Checkout.FetchBack.FetchBackPurchaseList = "";

            for (var iItems = 0; iItems < GroupIds.length; ++iItems)
            {
                //var ItemProperties = CartArray[iItems].split("|");
                var ItemProperties = CartArray[parseInt(GroupIds[iItems])].split("|");
                // Examples:
                // MAINPRODUCT|907|PRODUCTNAME|1|299.00|1.00
                // BUNDLE|757|3M Double Sided Tape - 1" Squares|4|2.00|1.00
                // <ParentID>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>
                // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>
                // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>|<CouponPrice>|<Coupon>|<No Free Shipping>|<Flat Rate Shipping>
                // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>|<CouponPrice>|<Coupon>|<No Free Shipping>|<Flat Rate Shipping>|<Non Shippable>

                if(Checkout.ThankyouPageShowParam == "&show=4" && "4932,76426,88439,135792,".indexOf(ItemProperties[2]+",") > -1)
                {
                    Checkout.ThankyouPageShowParam = "&show=1";
                }

                if(Checkout.ThankyouPageShowParam == "&show=1" && "134775,1533,2869,1532,".indexOf(ItemProperties[2]+",") > -1)
                {
                    Checkout.ThankyouPageShowParam = "&show=3";
                }

                if(
                    ItemProperties[2] == "134775"
                    || ItemProperties[2] == "1533"
                    || ItemProperties[2] == "2869"
                    || ItemProperties[2] == "1532"
                  )
                {
                    Checkout.UseConsultantMsg = true;
                }

                if (ItemProperties[2] == "76495")
                {
                    Checkout.Cart.ContainsSmartMoneyPackage = true;
                    Checkout.eBillme.Enable(false);
                }

                /// Monitoring Service
                switch (ItemProperties[2])
                {
                    case "1537": /// pre-prg (re-Programming for Alarm Panel)
                        Checkout.Cart.PreprogrammingIncluded = true;
                        break;
                        
                    case "1532": /// mon-pwrk-Standard (Monitoring Paperwork for Standard Monitoring)
                    case "1533": /// mon-pwrk-LiveWatch (Monitoring Paperwork for LiveWatch)
                        Checkout.Cart.StandardMonitoring = true;
                        break;

                    case "2869": /// mon-pwrk-LiveWatch&Monitoring (Monitoring Paperwork for LiveWatch w Monitoring)
                        Checkout.Cart.InteractiveMonitoring = true;
                        break;

                    case "76416": /// Sparrow VoIP Broadband Module
                        Checkout.Cart.VoipModuleInclude = true;
                        break;

                    case "426":   /// GSM Cellular Module
                    case "1862":  /// GE Simon XT GSM Wireless Cellular Module
                    case "1347":  /// GE Concord 4 GSM Cellular Module
                    case "168":   /// GSM Cellular Communicator
                    case "86624": /// Telguard TG-1 Express Wireless Communicator for LiveWatch
                        Checkout.Cart.GsmModuleIncluded = true;
                        break;
                }


                if (ItemProperties[1] == "0")
                {

                    Checkout.FetchBack.FetchBackPurchaseList += ItemProperties[2];
                    Checkout.CommissionJunctionPixel.AddItem(ItemProperties[2],Checkout.ToMoney(ItemProperties[5],false), ItemProperties[4])


                    ItemHTML = ItemHTML.replace(/_#GroupId#_/g, ItemProperties[0]);
                    ItemHTML = ItemHTML.replace(/_#NsId#_/g, ItemProperties[2]);
                    ItemHTML = ItemHTML.replace(/_#ImgLocation#_/g, ItemProperties[8]);
                    ItemHTML = ItemHTML.replace(/_#ItemLocation#_/g, ItemProperties[9]);
                    ItemHTML = ItemHTML.replace(/_#ItemName#_/g, ItemProperties[3]);
                    ItemHTML = ItemHTML.replace(/_#Sku#_/g, ItemProperties[7]);
                    ItemHTML = ItemHTML.replace(/_#Qty#_/g, ItemProperties[4]);

                    var DiscountPrice = parseFloat(ItemProperties[10]);
                    var ReqularPrice = parseFloat(ItemProperties[5]);

                    UnitDiscountPrice += DiscountPrice;
                    UnitPrice += ReqularPrice;

                    

                    BaseQty = parseInt(ItemProperties[4]);
                    Checkout.Cart.Qty += BaseQty;

                    if (ItemProperties[14] == "false")
                    {
                        Checkout.Cart.NoShipping = 0;
                    }
                }
                else
                {
                    if (CustomizationsHTML.length == 0)
                    {
                        CustomizationLink = "View&nbsp;Options";

                    }
                    else
                    {
                        CustomizationsHTML += "<br />";
                    }

                    CustomizationsHTML += ItemProperties[3];

                    var DiscountPrice = parseFloat(ItemProperties[10]);
                    var ReqularPrice = parseFloat(ItemProperties[5]);

                    UnitDiscountPrice += (parseInt(ItemProperties[4]) / BaseQty) * DiscountPrice;
                    UnitPrice += (parseInt(ItemProperties[4]) / BaseQty) * ReqularPrice;
                }

                //UnitPrice += parseFloat(ItemProperties[5]);
                //TotalPrice += parseFloat(ItemProperties[4])*parseFloat(ItemProperties[5]);

                var ItemQty = parseInt(ItemProperties[4]);
                var ItemWeight = parseFloat(ItemProperties[6]);
                var IsItemNoFreeShip = ItemProperties[12].toLowerCase();
                var ItemFlatShipRate = parseFloat(ItemProperties[13]);
                Checkout.Cart.Weight += ItemQty * ItemWeight;

                /// Use Flat Rate shipping over "No Free Shipping"
                if (ItemFlatShipRate == 0)
                {
                    if (IsItemNoFreeShip == "true")
                    {
                        Checkout.Cart.NoFreeShipWeight += ItemQty * ItemWeight;
                        Checkout.Cart.PieceCount += ItemQty;
                    }
                }
                else
                {
                    Checkout.Cart.FlatRateShip += ItemQty * ItemFlatShipRate;
                }
                //Checkout.Cart.SubTotal += parseFloat(ItemProperties[4])*parseFloat(ItemProperties[5]);
            }
/*
            alert(
            Checkout.Cart.MonitoringServiceType + "-" +
            Checkout.Cart.StandardMonitoring + "-" +
            Checkout.Cart.InteractiveMonitoring + "-" +
            Checkout.Cart.PreprogrammingIncluded + "-" +
            Checkout.Cart.GsmModuleIncluded + "-" +
            Checkout.Cart.VoipModuleInclude
            );
*/            
            //alert("NoShippingWeight " + Checkout.Cart.NoFreeShipWeight + "\r\nPieceCount " + Checkout.Cart.PieceCount + "\r\nFlatRateShipping " + Checkout.Cart.FlatRateShip);
            /// This section of code supports line item discounts.
            /// currenly line item discounts is disabled on the server.
            /// The code remains here should line item discounts be re-enabled.            
            if (UnitDiscountPrice > 0)
            { /// Set the discount price

                TotalPrice += UnitDiscountPrice * BaseQty;
                Checkout.Cart.SubTotal += TotalPrice;

                /// Strike through the Reqular price
                ItemHTML = ItemHTML.replace(/_#PriceStyles#_/g, "text-decoration: line-through;");

                /// Write-in the discount price
                ItemHTML = ItemHTML.replace(/_#DiscountPrice#_/g, Checkout.ToMoney(UnitDiscountPrice));
                ItemHTML = ItemHTML.replace(/_#DiscountTotal#_/g, Checkout.ToMoney(TotalPrice));

                /// show the discount price
                ItemHTML = ItemHTML.replace(/_#DiscountDisplay#_/g, "block");
            }
            else
            { /// Use the regular price
                TotalPrice += UnitPrice * BaseQty;
                Checkout.Cart.SubTotal += TotalPrice;

                /// Clear discount price
                ItemHTML = ItemHTML.replace(/_#DiscountPrice#_/g, "");
                ItemHTML = ItemHTML.replace(/_#DiscountTotal#_/g, "");

                /// hide the discount price
                ItemHTML = ItemHTML.replace(/_#DiscountDisplay#_/g, "none");

            }

            ItemHTML = ItemHTML.replace(/_#Price#_/g, Checkout.ToMoney(UnitPrice));
            ItemHTML = ItemHTML.replace(/_#Total#_/g, Checkout.ToMoney(TotalPrice));
            ItemHTML = ItemHTML.replace(/_#CustomizationLink#_/g, CustomizationLink);
            ItemHTML = ItemHTML.replace(/_#Customizations#_/g, CustomizationsHTML);

            // Add the item to the list
            ItemListHTML += ItemHTML;
        }

        var SessionId = Safemart.GetSession();


        document.getElementById("CartRef").innerHTML = "Cart Reference: " + SessionId;


        document.getElementById("CartItems").innerHTML = "<table border='0' width='100%' cellspacing='0' cellpadding='0' style='padding-right:20px;'>" +
            ItemListHTML + "</table>";
    }

    if (Checkout.Customer.Ship.Zip.length > 0)
    {
        /// Update Shipping 
        Checkout.Customer.Ship.GetMethods();
    }

    Checkout.SetTotals();
    Checkout.Cart.ApplyCoupon();


}

Checkout.Cart.ApplyCoupon = function()
{

    //document.getElementById("CardMessage").innerHTML = ""

    /// Clear values
    /*
    if (Checkout.Cart.DiscountType != "")
    {
    Checkout.Cart.Discount = "";
    Checkout.Cart.DiscountValue = 0;
    Checkout.Cart.DiscountType = "";
    Checkout.Customer.Ship.MethodsReturn(Checkout.Customer.Ship.Raw);
    }
    */

    if (Checkout.Cart.PromotionCode.length > 0)
    {
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", Safemart.GetSession());
        aParameters.Add("customer_InternalID", Checkout.Customer.InternalID());
        aParameters.Add("couponCode", Checkout.Cart.PromotionCode);

        wsi._Soap.AddCall("ValidateCoupon", Checkout.Cart.CouponReturn, aParameters);
    }
    else
    {
        /// Reset totals
        Checkout.SetTotals();
    }
}

Checkout.Cart.CouponReturn = function(returnValue)
{
    if (returnValue.substring(0, 5) == "error")
    {
        /// Clear the discount
        Checkout.Cart.Discount = "";
        Checkout.Cart.DiscountValue = 0;
        Checkout.Cart.DiscountType = "";
        Checkout.Cart.PromotionCode = "";
        wsi._Cookie.ClearCrumb("cp");
        
        alert(returnValue.substring(7))
    }
    else
    {
        Checkout.Cart.Discount = returnValue;
        if (returnValue.slice(0, 1) == "$")
        {
            Checkout.Cart.DiscountValue = parseFloat(returnValue.slice(1));
            Checkout.Cart.DiscountType = "$";
        }
        else if (returnValue.slice(-1) == "%")
        {
            Checkout.Cart.DiscountValue = parseInt(returnValue.slice(0, -1));
            Checkout.Cart.DiscountType = "%";
        }
        else if (returnValue.slice(0, 1) == "#")
        {
            Checkout.Cart.DiscountValue = returnValue.slice(1);
            Checkout.Cart.DiscountType = "S";
            Checkout.Customer.Ship.Type = Checkout.Cart.DiscountValue;
            Checkout.Customer.Ship.MethodsReturn(Checkout.Customer.Ship.Raw);

            alert("Free shipping has been applied to your cart.");
        }
        else
        {/// display message
            /// This should only be called if using a Line Item Discounts.
            alert(returnValue);
        }
    }

    Checkout.SetTotals();
}

/// Converts a float value to a Money String
Checkout.ToMoney = SWH.ToMoney;
/*
Checkout.ToMoney = function(value)
{

// convert to string
value = "" + value;
    
if (value.indexOf(".") == -1)
{
value += ".00";
}
    
if (value.indexOf(".") < value.length - 3)
{/// round to two decimals
//value = Math.round(parseFloat(value)*100)/100
        
value = Checkout.RoundMoney(value);
        
/// Make the value a string again
value = ""+value;
        
}
       
//alert(value + "  " + value.slice(-2,-1))
if (value.slice(-2,-1) == ".")
{/// second to last char is a . -- pad the value with zero.
value += "0";
}
   


// add the $        
value = "$" + value;
        
return value;
}
*/

Checkout.RoundMoney = SWH.RoundMoney;
/*
Checkout.RoundMoney = function(value)
{
return Math.round(parseFloat(value)*100)/100
}
*/

Checkout.SetTotals = function()
{
    /// CheckoutTotal will be null if the page load is not complete 
    if (document.getElementById("CheckoutTotal") != null)
    {
        var Discount = 0;

        if (Checkout.Cart.DiscountType == "$")
        {
            Discount = Checkout.Cart.DiscountValue;
        }
        else if (Checkout.Cart.DiscountType == "%")
        {
            Discount = Checkout.RoundMoney((Checkout.Cart.DiscountValue / 100) * Checkout.Cart.SubTotal);
        }

        if (document.getElementById("CheckoutDiscount") != null)
        {
            if (Discount > 0)
            {
                document.getElementById("CheckoutDiscount").style.color = "red";
            }
            else
            {
                document.getElementById("CheckoutDiscount").style.color = "black";
            }
        }

        var ShipText = ""
        if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == Checkout.Customer.Ship.Type)
        {
            ShipText = "(Free)"
        }

        var Taxes = 0;
        var TaxState = (Checkout.Customer.Bill.SameAsShip == true ? Checkout.Customer.Ship.State : Checkout.Customer.Bill.State);
        /*
        if (
        (Checkout.Customer.Bill.SameAsShip == true && Checkout.Customer.Ship.Country == "US" && Checkout.Customer.Ship.State == "KS")
        ||
        (Checkout.Customer.Bill.SameAsShip == false && Checkout.Customer.Bill.Country == "US" && Checkout.Customer.Bill.State == "KS")
        )
        {
        */
        if (Checkout.Customer.Ship.Country == "US")
        {
            switch (TaxState)
            {
                case "KS":
                    Taxes = (Checkout.TaxRateKs / 100) * Checkout.Cart.SubTotal;
                    break;

                case "IL":
                    Taxes = (Checkout.TaxRateIl / 100) * Checkout.Cart.SubTotal;
                    break;
            }

        }


        document.getElementById("CheckoutSubTotal").innerHTML = Checkout.ToMoney(Checkout.Cart.SubTotal);
        document.getElementById("CheckoutDiscount").innerHTML = (Discount > 0 ? "-" : "") + Checkout.ToMoney(Discount);
        document.getElementById("CheckoutDiscountText").innerHTML = (Discount > 0 ? "(" + Checkout.Cart.Discount + ")" : "");
        document.getElementById("CheckoutShippingCost").innerHTML = Checkout.ToMoney(Checkout.Customer.Ship.Cost);
        document.getElementById("CheckoutFreeShippingText").innerHTML = ShipText;

        Checkout.Cart.Tax = Taxes;
        document.getElementById("CheckoutTax").innerHTML = Checkout.ToMoney(Taxes);

        Checkout.Cart.Total = (Checkout.Cart.SubTotal - Discount) + Checkout.Customer.Ship.Cost + Taxes
        document.getElementById("CheckoutTotal").innerHTML = Checkout.ToMoney(Checkout.Cart.Total);
    }
}

Checkout.GoogleCheckout = function()
{
    if (Checkout.Cart.IsEmpty)
    {
        alert(Checkout.Cart.EmptyText);
    }
    else
    {
        var _sSessionId = Safemart.GetSession();
        document.location.href = "/checkout/GoogleCheckout.aspx?id=" + _sSessionId;
    }
}

Checkout.EnableSmartMoneyOptions = function()
{

}

Checkout.PlaceOrder = function()
{
    /// Clear the order error
    Checkout.OrderError = false;

    if (Checkout.Cart.NoShipping)
    {
        Checkout.Customer.Bill.SameAsShip = false
    }

    if (document.getElementById("CardMessage") != null)
    {
        /// Reset the Message
        document.getElementById("CardMessage").innerHTML = ""
    }
    //alert("PlaceOrder - sessionID: " + wsi._Cookie.GetCrumb("SessionID") + Checkout.Cart.Name);
    var aParameters = new wsi._Parameters();
    //window.status = Checkout.Customer.InternalID();
    aParameters.Add("sessionId", Safemart.GetSession() + Checkout.Cart.Name);
    aParameters.Add("customer_InternalID", Checkout.Customer.InternalID());
    aParameters.Add("customer_SalesRep", Checkout.Customer.SalesRep);
    aParameters.Add("customer_LeadSource", Checkout.Customer.LeadSource);
    aParameters.Add("customer_CampaignKeyword", Checkout.Customer.CampaignKeyword);
    aParameters.Add("Opportunity_Type", Checkout.Customer.OpportunityType);
    aParameters.Add("customer_Email", Checkout.Customer.Email);
    aParameters.Add("customer_Password", Checkout.Customer.Password);

    aParameters.Add("ship_InternalId", Checkout.Customer.Ship.InternalId);
    aParameters.Add("ship_FirstName", Checkout.Customer.Ship.FirstName);
    aParameters.Add("ship_LastName", Checkout.Customer.Ship.LastName);
    aParameters.Add("ship_Company", Checkout.Customer.Ship.Company);
    aParameters.Add("ship_AddressLine1", Checkout.Customer.Ship.AddressLine1);
    aParameters.Add("ship_AddressLine2", Checkout.Customer.Ship.AddressLine2);
    aParameters.Add("ship_City", Checkout.Customer.Ship.City);
    aParameters.Add("ship_State", Checkout.Customer.Ship.State);
    aParameters.Add("ship_Zip", Checkout.Customer.Ship.Zip);
    aParameters.Add("ship_Country", Checkout.Customer.Ship.Country);
    aParameters.Add("ship_Phone", Checkout.Customer.Ship.Phone);
    aParameters.Add("ship_Type", Checkout.Customer.Ship.Type);
    aParameters.Add("ship_Cost", Checkout.Customer.Ship.Cost);
    aParameters.Add("ship_Memo", Checkout.Customer.Ship.Memo + " " + Checkout.Cart.AdditionalComments);

    aParameters.Add("bill_InternalId", Checkout.Customer.Bill.InternalId);
    aParameters.Add("bill_SameAsShip", (Checkout.Customer.Bill.SameAsShip ? "true" : "false"));
    aParameters.Add("bill_FirstName", Checkout.Customer.Bill.FirstName);
    aParameters.Add("bill_LastName", Checkout.Customer.Bill.LastName);
    aParameters.Add("bill_Company", Checkout.Customer.Bill.Company);
    aParameters.Add("bill_AddressLine1", Checkout.Customer.Bill.AddressLine1);
    aParameters.Add("bill_AddressLine2", Checkout.Customer.Bill.AddressLine2);
    aParameters.Add("bill_City", Checkout.Customer.Bill.City);
    aParameters.Add("bill_State", Checkout.Customer.Bill.State);
    aParameters.Add("bill_Zip", Checkout.Customer.Bill.Zip);
    aParameters.Add("bill_Country", Checkout.Customer.Bill.Country);
    aParameters.Add("bill_Phone", Checkout.Customer.Bill.Phone);

    aParameters.Add("card_InternalId", Checkout.Customer.CreditCard.InternalId);
    aParameters.Add("card_Type", Checkout.Customer.CreditCard.Type);
    aParameters.Add("card_NameOnCard", Checkout.Customer.CreditCard.NameOnCard);
    aParameters.Add("card_Number", Checkout.Customer.CreditCard.Number);
    aParameters.Add("card_ExpirationMonth", Checkout.Customer.CreditCard.ExpirationMonth);
    aParameters.Add("card_ExpirationYear", Checkout.Customer.CreditCard.ExpirationYear);
    aParameters.Add("card_CVV2", Checkout.Customer.CreditCard.CVV2);
    aParameters.Add("promotionCode", Checkout.Cart.PromotionCode);
    aParameters.Add("championStatus", Checkout.Customer.ChampionStatus);
    aParameters.Add("paymentMethod", Checkout.Customer.PaymentMethod());
    aParameters.Add("eBillMeAccount", Checkout.eBillme.GetAccountNumber());
    aParameters.Add("eBillMeOrderId", Checkout.eBillme.GetOrderNumber());
    aParameters.Add("ssn", Checkout.Customer.SSN);


    wsi._Soap.AddCall("PlaceOrder", Checkout.PlaceOrderReturn, aParameters);

    /// HasAccount == false verifies that HasAccount is NOT true and NOT null
    if (Checkout.Customer.HasAccount() == false && Checkout.Customer.InternalID().length == 0)//  Checkout.Customer.Email.indexOf("safemart.com") > -1)
    {
        Checkout.Notification_CreateAccount();
    }
    else
    {
        Checkout.Notificaton_SubmitOrder();
    }
}

Checkout.CreatingPassword = false;
Checkout.SavePassword = false;

Checkout.Notification_CreateAccount = function()
{
    Checkout.CreatingPassword = true;


    document.getElementById("CheckoutNotificationCaption").innerHTML = "Submitting Order";
    document.getElementById("CheckoutNotificationMessage").innerHTML = document.getElementById("CreatAccountNotification").innerHTML;
    YAHOO.example.container.panel1.show();
}

Checkout.Notification_CreateAccount_GetPassword = function()
{
    Checkout.CreatingPassword = true;

    document.getElementById("CheckoutNotificationCaption").innerHTML = "Submitting Order";
    document.getElementById("CheckoutNotificationMessage").innerHTML = document.getElementById("GetPasswordNotification").innerHTML;
    YAHOO.example.container.panel1.show();
}

Checkout.Notification_CreatAccountReturn = function(returnValue)
{


    var PasswordConfirmed = true;
    var PasswordValid = true;

    if (returnValue != 'save')
    {// do not save the password.
        Checkout.Customer.Password = "";
        Checkout.Customer.PassConfirm = "";
    }
    else
    {
        Checkout.SavePassword = true;

        PasswordConfirmed = (Checkout.Customer.Password == Checkout.Customer.PassConfirm ? true : false)
        PasswordValid = Checkout.Customer.ValidatePassword();
        //window.status = PasswordConfirmed + " " + PasswordValid;        
        if (!PasswordConfirmed || !PasswordValid)
        {
            if (!PasswordConfirmed)
            {
                //document.getElementById("CreateAccountMsg").innerHTML = "Your Password Confirmation is different than your Password. Please re-type your Password.";
                alert("Your Password Confirmation is different than your Password. Please re-type your Password.");
            }
            else
            {
                //document.getElementById("CreateAccountMsg").innerHTML = "Your password must be at least 6 characters long and contain one number.";
                alert("Your password must be at least 6 characters long and contain one number.");
            }
            /*            
            document.getElementById("CreateAccountMsg").style.color = "red";
            document.getElementById("txtAccountPassword").value = "";
            document.getElementById("txtAccountPassConfirm").value = "";
            
            Checkout.Customer.Password = "";
            Checkout.Customer.PassConfirm = "";
            */

        }
    }

    if (PasswordConfirmed && PasswordValid)
    {
        Checkout.CreatingPassword = false;

        if (Checkout.PlaceOrderReturnValue.length > 0)
        {
            Checkout.Notificaton_SubmitOrder();
            Checkout.PlaceOrderReturn2();
        }
        else
        {
            Checkout.Notificaton_SubmitOrder();
        }
    }
}

Checkout.ChangePassword = function()
{
    var aParameters = new wsi._Parameters();
    aParameters.Add("customer_InternalID", Checkout.Customer.InternalID());
    aParameters.Add("customer_Email", Checkout.Customer.Email);
    aParameters.Add("customer_Password", Checkout.Customer.Password);

    wsi._Soap.AddCall("ChangeCustomerPassword", Checkout.ChangePasswordReturn, aParameters);
}

Checkout.ChangePasswordReturn = function(returnValue)
{
    //alert(returnValue);
}
Checkout.Notificaton_SubmitOrder = function()
{
    if (document.getElementById("CheckoutNotificationCaption") != null)
    {
	var ConsultantMsg = ""

        if (Checkout.UseConsultantMsg)
        {
		ConsultantMsg = "One of our expert Security Consultants will be calling you to finalize the configuration on your order.<br><b>Once we have completed this configuration</b>, your order will ship within one business day.";
        }

        document.getElementById("CheckoutNotificationCaption").innerHTML = "Submitting Order";
        document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Submitting your order.<br /><img src='/img/images/progress.gif' alt=''></center><br /><br />" + ConsultantMsg;

        YAHOO.example.container.panel1.show();
    }
}

Checkout.PlaceOrderReturnValue = "";

Checkout.PlaceOrderReturn = function(returnValue)
{
    Checkout.PlaceOrderReturnValue = returnValue;

    if (!Checkout.CreatingPassword)
    {
        Checkout.PlaceOrderReturn2();
    }

}
Checkout.ThankyouPage = "thank-you.htm";
Checkout.ThankyouPageParam = "";
Checkout.ThankyouPageShowParam = "";

Checkout.PlaceOrderReturn2 = function()
{
    var returnValue = Checkout.PlaceOrderReturnValue;

    YAHOO.example.container.panel1.hide(); /// close notificaion window.

    /// Clear additional comments
    wsi._Cookie.CartComments("");
    Checkout.Cart.AdditionalComments

    if (returnValue.indexOf("InternalId=") > -1)
    {
        Checkout.Customer.InternalID(returnValue.substring(returnValue.indexOf("InternalId=") + 11));
        returnValue = returnValue.substring(0, returnValue.indexOf("InternalId=") - 1);
    }

    if (returnValue.indexOf("Order created successfully") > -1)
    {

        Checkout.FetchBack.Purchase(Checkout.FetchBack.FetchBackPurchaseList);

        if (Checkout.Customer.InternalID().length > 0 && Checkout.SavePassword)
        {
            document.getElementById("CardMessage").innerHTML = "Creating User account...";
            Checkout.ChangePassword();
        }

        var _cOrderId = "";
        /// Strip off the order id
        if (returnValue.indexOf("OrderId=") > -1)
        {
            _cOrderId = returnValue.substring(returnValue.indexOf("|OrderId=") + 9);
            returnValue = returnValue.substring(0, returnValue.indexOf("OrderId=") - 1);
        }
        
        Checkout.CommissionJunctionPixel.PostPixel(_cOrderId);

        if (_cOrderId.length > 0)
        {
            Checkout.Google.Analytics(_cOrderId);
        }

        var ConfiramtionUrl = ""
        if (Checkout.eBillme.GetConfirmationPageUrl().length > 0)
        {
            ConfiramtionUrl = "&confirmationpageurl=" + Checkout.eBillme.GetConfirmationPageUrl();
        }


        if (Checkout.Cart.StandardMonitoring)
        {
            if (Checkout.Cart.VoipModuleInclude)
            {
                Checkout.Cart.MonitoringServiceType = "2";
            }
            else if (Checkout.Cart.GsmModuleIncluded)
            {
                Checkout.Cart.MonitoringServiceType = "3";
            }
            else
            {
                Checkout.Cart.MonitoringServiceType = "1";
            }
        }

        if (Checkout.Cart.InteractiveMonitoring)
        {
            Checkout.Cart.MonitoringServiceType = "4";
        }

        if (Checkout.Cart.PreprogrammingIncluded && Checkout.Cart.MonitoringServiceType == 0)
        {
            Checkout.Cart.MonitoringServiceType = "pre-prg";
        }

        var ServiceTypeParam = "";
        if (Checkout.Cart.MonitoringServiceType != "")
        {
            ServiceTypeParam = "&service_type=" + Checkout.Cart.MonitoringServiceType;
        }
        
        /*
        alert(
        Checkout.Cart.MonitoringServiceType + "-" +
        Checkout.Cart.StandardMonitoring + "-" +
        Checkout.Cart.InteractiveMonitoring + "-" +
        Checkout.Cart.PreprogrammingIncluded + "-" +
        Checkout.Cart.GsmModuleIncluded + "-" +
        Checkout.Cart.VoipModuleInclude + "-" +
        ServiceTypeParam
        );
        */
        
        var Host = ""
        /// The Quarantine site does not allow non-secure pages.
        if (document.location.host.toLowerCase().indexOf("quarantine") == -1)
        {
            Host = "http://" + document.location.host;
        }

        var ThankYou = "";
        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            ThankYou = "thank-you-sm.htm";
        }
        else
        {
            ThankYou = Checkout.ThankyouPage;
        }

        //document.location.href = Host + "/" + ThankYou + "?orderId=" + _cOrderId + "&total=" + Checkout.RoundMoney(Checkout.Cart.Total) + "&qty=" + Checkout.Cart.Qty + ServiceTypeParam + ConfiramtionUrl + Checkout.ThankyouPageParam;
        Checkout.RedirectUrl = Host + "/" + ThankYou + "?orderId=" + _cOrderId + "&total=" + Checkout.RoundMoney(Checkout.Cart.Total) + "&subtotal=" + Checkout.RoundMoney(Checkout.Cart.SubTotal) + "&qty=" + Checkout.Cart.Qty + ServiceTypeParam + ConfiramtionUrl + Checkout.ThankyouPageParam + Checkout.ThankyouPageShowParam;
        setTimeout("Checkout.Redirect()",2000);
    }
    else
    {
        if (Checkout.PayPalOrder)
        {
            document.getElementById("PayPalMessage").innerHTML = returnValue.replace("Error: ", "");
        }
        else
        {
            //document.getElementById("CardMessage").innerHTML = returnValue.replace("Error: ", "");
            alert(returnValue.replace("Error: ", ""));
            Checkout.OrderError = true;
        }
    }
}


Checkout.RedirectUrl = "";
Checkout.Redirect = function()
{
    document.location.href = Checkout.RedirectUrl;
}

Checkout.Google = new Object();
Checkout.Google.SubPageVisited = new Array();
Checkout.Google.TrackSubPage = function(subPage)
{
    //alert(Checkout.Google.SubPageVisited[subPage]);
    if (Checkout.Google.SubPageVisited[subPage] != true)
    {

        /// Mark sub page visited.
        Checkout.Google.SubPageVisited[subPage] = true;

        /// Google Analytics - page tracking
        if (Checkout.Customer.InternalID().length == 0)
        {/// The customer is NOT logged in
            //pageTracker._trackPageview("/Checkout/" + Checkout.GoogleAnalyticsSteps[subPage]);
            if (typeof (_gaq) != "undefined")
            {
                _gaq.push(['_trackPageview', "/Checkout/" + Checkout.GoogleAnalyticsSteps[subPage]]);
                //alert("/Checkout/" + Checkout.GoogleAnalyticsSteps[subPage])
            }
        }
        else
        {/// The customer is  logged in

            /// Do not track Shipping Address for authenticated customers
            if (subPage != 1)
            {
                //pageTracker._trackPageview("/Checkout/" + Checkout.GoogleAnalyticsReturnCustSteps[subPage]);
                if (typeof (_gaq) != "undefined")
                {
                    _gaq.push(['_trackPageview', "/Checkout/" + Checkout.GoogleAnalyticsReturnCustSteps[subPage]]);
                    //alert("/Checkout/" + Checkout.GoogleAnalyticsReturnCustSteps[subPage])
                }
            }
        }
    }
}
Checkout.Google.Analytics = function(orderId)
{
    if (typeof (_gaq) != "undefined")
    {
        //pageTracker._addTrans(
        _gaq.push(['_addTrans',
        orderId,                           // Order ID
        "",                                // Affiliation
        "" + Checkout.Cart.Total,          // Total
        "" + Checkout.Cart.Tax,            // Tax
        "" + Checkout.Customer.Ship.Cost,  // Shipping
        Checkout.Customer.Ship.City,       // City
        Checkout.Customer.Ship.State,      // State
        Checkout.Customer.Ship.Country     // Country
        //]);
        ]);
        var CartArray = Checkout.Cart.Raw.split("||");

        for (var iItems = 0; iItems < CartArray.length; ++iItems)
        {

            var ItemProperties = CartArray[iItems].split("|");
            // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>

            //pageTracker._addItem(
            _gaq.push(['_addItem',
                orderId,           // Order ID
                ItemProperties[7], // SKU
                ItemProperties[3], // Product Name
                "",                // Category
                ItemProperties[5], // Price
                ItemProperties[4]  // Quantity
              //);
              ]);
        }

        //pageTracker._trackTrans();
        _gaq.push(['_trackTrans']);
    }
}

Checkout.CurrentStep = 0; //skip the login step
Checkout.Progress = 0; // start with the shipping address

Checkout.Steps = new Array();
Checkout.Steps[0] = "stepCart";
Checkout.Steps[1] = "stepAddress";
Checkout.Steps[2] = "stepBillingAddress";
Checkout.Steps[3] = "stepShippingOptions";
Checkout.Steps[4] = "stepPayment";

Checkout.GoogleAnalyticsSteps = new Array();
Checkout.GoogleAnalyticsSteps[0] = "Cart";
Checkout.GoogleAnalyticsSteps[1] = "ShippingAddress";
Checkout.GoogleAnalyticsSteps[2] = "BillingAddress";
Checkout.GoogleAnalyticsSteps[3] = "ShippingMethods";
Checkout.GoogleAnalyticsSteps[4] = "BillingInformation";

Checkout.GoogleAnalyticsReturnCustSteps = new Array();
Checkout.GoogleAnalyticsReturnCustSteps[0] = "ReturnCustCart";
Checkout.GoogleAnalyticsReturnCustSteps[1] = "ReturnCustShippingAddress";
Checkout.GoogleAnalyticsReturnCustSteps[2] = "ReturnCustBillingAddress";
Checkout.GoogleAnalyticsReturnCustSteps[3] = "ReturnCustShippingMethods";
Checkout.GoogleAnalyticsReturnCustSteps[4] = "ReturnCustBillingInformation";

Checkout.NextStep = function()
{
    /// If there are no products requiring shipping, skip the shipping address and go to billing
    if (Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep + 1] == "stepAddress")
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 2]);
    }
    /// if the next step is the billing address
    /// and the billing address is the same as the shipping
    //// skip the billing address step.
    else if (Checkout.Steps[Checkout.CurrentStep + 1] == "stepBillingAddress"
        && Checkout.Customer.Bill.SameAsShip)
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 2]);
    }
    else if (Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep + 1] == "stepShippingOptions")
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 2]);
    }
    else
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 1]);
    }
}

Checkout.PrevStep = function()
{
    /// if the previous step is the billing address
    /// and the billing address is the same as the shipping
    //// go to the shipping address step.
    if (!Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep - 1] == "stepBillingAddress"
        && Checkout.Customer.Bill.SameAsShip)
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep - 2]);
    }
    else if (Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep - 1] == "stepShippingOptions")
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep - 2]);
    }
    else
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep - 1]);
    }
}

Checkout.ShowStep = function(showThis)
{
    if (showThis != "stepAddress")
    {
        document.location.hash = "checkouttop";
    }

    Checkout.CollapseStep(Checkout.Steps[Checkout.CurrentStep]);
    Checkout.CurrentStep = Checkout.Steps.find(showThis);

    var ThisStep = document.getElementById(showThis);
    var ThisCaption = document.getElementById(showThis + "-Caption");
    var ThisBody = document.getElementById(showThis + "-Body");
    var ThisExpandImage = document.getElementById(showThis + "-ExpandImage");

    // Show the Step
    ThisStep.style.display = "block";
    ThisCaption.style.display = "block";
    ThisBody.style.display = "block";

    // Set the expand image
    if (showThis == "stepCart")
    {
        //ThisExpandImage.src = "../graphics/minus_compact.png"
    }

    Checkout.SetProgress();

    Checkout.Google.TrackSubPage(Checkout.CurrentStep);
}

Checkout.ActivateStep = function(activateThis)
{
    var ThisStep = document.getElementById(activateThis);
    var ThisCaption = document.getElementById(activateThis + "-Caption");
    var ThisBody = document.getElementById(activateThis + "-Body");

    // Show the Step
    ThisStep.style.display = "block";
    ThisCaption.style.display = "block";
    ThisBody.style.display = "block";

}

Checkout.SetProgress = function()
{

    var ActiveGraphic = (Checkout.CurrentStep < 2 ? 1 : Checkout.CurrentStep - 1)

    // Set the current step active
    if (Checkout.CurrentStep > 0)
    {
        var ThisProgress = document.getElementById("Progress" + ActiveGraphic);
        //if (ThisProgress.innerHTML.length == 0 || ThisProgress.innerHTML.indexOf("inactive") > -1)
        if (ThisProgress.src.indexOf("inactive") > -1)
        {
            //ThisProgress.innerHTML = "<img src='/graphics/cart-progress" + ActiveGraphic + "-active.gif'>";
            ThisProgress.src = "/graphics/cart-progress" + ActiveGraphic + "-active.gif";
        }
    }

    // Set the next steps inactive
    for (var i = ActiveGraphic + 1; i < 4; ++i)
    {
        var ThisProgress = document.getElementById("Progress" + i);
        if (ThisProgress.innerHTML.indexOf("inactive") == -1)
        {
            //ThisProgress.innerHTML = "<img src='/graphics/cart-progress" + i + "-inactive.gif'>";
            ThisProgress.src = "/graphics/cart-progress" + i + "-inactive.gif";
        }
    }

    Checkout.Progress = Checkout.CurrentStep;
}

Checkout.CollapseStep = function(hideThis)
{
    var ThisStep = document.getElementById(hideThis);
    var ThisCaption = document.getElementById(hideThis + "-Caption");
    var ThisBody = document.getElementById(hideThis + "-Body");
    var ThisExpandImage = document.getElementById(hideThis + "-ExpandImage");

    ThisStep.style.display = "none";
    //ThisBody.style.display = "none";

    // Set the expand image
    //ThisExpandImage.src = "../graphics/plus_compact.png"

    // Always collapse the Login
    document.getElementById("stepCart-Body").style.display = "none";
    //document.getElementById("stepLogin-ExpandImage").src = "../graphics/plus_compact.png";
}

Checkout.ToggleStep = function(toggleThis)
{

    var ThisBody = document.getElementById(toggleThis + "-Body");

    if (ThisBody.style.display == "none")
    {
        Checkout.ShowStep(toggleThis);
    }
    else
    {
        Checkout.CollapseStep(toggleThis);
    }

}

Checkout.SetStateField = function(toggleThis)
{
    if (toggleThis == "Ship")
    {

        var sAddress = Checkout.Customer.Ship;
    }
    else
    {
        var sAddress = Checkout.Customer.Bill;
    }
    //alert(sAddress.Country)
    switch (sAddress.Country)
    {
        case "US":
            document.getElementById("txt" + toggleThis + "StateProvince").style.display = "none";
            document.getElementById("div" + toggleThis + "StateProvince").style.display = "block";
            //document.getElementById("opt"+toggleThis+"StateProvince").style.display = "inline";
            document.getElementById("div" + toggleThis + "StateProvince_Canada").style.display = "none";

            //document.getElementById("opt"+toggleThis+"StateProvince").value = sAddress.State;
            document.getElementById("opt" + toggleThis + "StateProvince").value = sAddress.StateDomestic;
            sAddress.State = sAddress.StateDomestic;
            break;


        case "CA":
            document.getElementById("txt" + toggleThis + "StateProvince").style.display = "none";
            document.getElementById("div" + toggleThis + "StateProvince").style.display = "none";
            //document.getElementById("opt"+toggleThis+"StateProvince").style.display = "none";
            document.getElementById("div" + toggleThis + "StateProvince_Canada").style.display = "block";
            //document.getElementById("opt"+toggleThis+"StateProvince_Canada").value = sAddress.State;

            document.getElementById("opt" + toggleThis + "StateProvince_Canada").value = sAddress.StateCanada;
            sAddress.State = sAddress.StateCanada;
            break;

        default:
            document.getElementById("txt" + toggleThis + "StateProvince").style.display = "block";
            document.getElementById("div" + toggleThis + "StateProvince").style.display = "none";
            document.getElementById("div" + toggleThis + "StateProvince_Canada").style.display = "none";
            //document.getElementById("txt"+toggleThis+"StateProvince").value = sAddress.State;  

            document.getElementById("txt" + toggleThis + "StateProvince").value = sAddress.StateInternational;
            sAddress.State = sAddress.StateInternational;
            break;


    }
}

Checkout.ToggleCountryField = function(toggleThis)
{


    if (toggleThis == "Ship")
    {

        var Address = Checkout.Customer.Ship;
    }
    else
    {
        var Address = Checkout.Customer.Bill;
    }

    if (document.getElementById("lbl" + toggleThis + "CountryID").style.display != "none")
    {/// Change to International


        /// Save State
        switch (Address.Country)
        {
            case "CA":
                Address.StateCanada = Address.State;
                break;

            case "US":
                Address.StateDomestic = Address.State;
                break;

            default:
                Address.StateInternational = Address.State;
                break;
        }

        /// Restore International Country
        Address.Country = Address.CountryInternational;

        /*
        /// Restore State
        switch(Address.Country)
        {
        case "CA":
        Address.State = Address.StateCanada;
        break;
                
        case "US":
        Address.State = Address.StateDomestic;
        break;
                
        default:
        Address.State = Address.StateInternational;
        break;
        }
        */



        document.getElementById("lbl" + toggleThis + "CountryID").style.display = "none";
        document.getElementById("txt" + toggleThis + "CountryID").style.display = "block";
        //document.getElementById("lnk"+toggleThis+"CountryToggle").innerHTML = "Click Here for Domestic Addresses";
        document.getElementById("lbl" + toggleThis + "StateProvince").innerHTML = "State/Province";
        document.getElementById("lbl" + toggleThis + "ZipPostalCode").innerHTML = "Zip/Postal Code";

        /// SHILL 9/15/08 Added 
        /// Switch to international Phone field
        document.getElementById("Domestic" + toggleThis + "Phone").style.display = "none";
        document.getElementById("International" + toggleThis + "Phone").style.display = "block";
        document.getElementById("txt" + toggleThis + "PhoneNumber").value = Address.Phone;
        /// End Added

    }
    else
    {/// Change to Domestic

        /// Save International Country
        Address.CountryInternational = Address.Country;
        /// Change to US
        Address.Country = "US";

        /// Save Internationl State
        if (Address.CountryInternational == "CA")
        {
            Address.StateCanada = Address.State;
        }
        else
        {
            Address.StateInternational = Address.State;
        }
        /// Restore Domestic State
        //Address.State = Address.StateDomestic;


        document.getElementById("lbl" + toggleThis + "CountryID").style.display = "block";
        document.getElementById("txt" + toggleThis + "CountryID").style.display = "none";
        //document.getElementById("lnk"+toggleThis+"CountryToggle").innerHTML = "Click Here for International Addresses";
        document.getElementById("lbl" + toggleThis + "StateProvince").innerHTML = "State";
        document.getElementById("lbl" + toggleThis + "ZipPostalCode").innerHTML = "Zip Code";
        //document.getElementById("txt"+toggleThis+"StateProvince").value = document.getElementById("opt"+toggleThis+"StateProvince").value;

        /// SHILL 9/15/08 Added
        /// Switch to domestic phone format
        document.getElementById("Domestic" + toggleThis + "Phone").style.display = "block";
        document.getElementById("International" + toggleThis + "Phone").style.display = "none";
        Checkout.UpdatePhone(toggleThis);
        /// End Added
    }

    Checkout.SetStateField(toggleThis);
}

Checkout.HideAllSteps = function()
{
    for (var i = 0; i < Checkout.Steps.length; i++)
    {
        document.getElementById(Checkout.Steps[i]).style.display = "none";
    }
}

Checkout.ShowSubstep = function(subStep)
{
    document.getElementById(subStep).style.display = "block";
}

Checkout.HideSubstep = function(subStep)
{
    document.getElementById(subStep).style.display = "None";
}

Checkout.ShowEbillmeSubstep = function()
{
    Checkout.HideSubstep('substepCardInfo');
    Checkout.ShowSubstep('substepEbillme');
    document.getElementById("uiSubmitBtn").style.display = "none";
}

Checkout.ShowCreditCardSubstep = function()
{
    Checkout.HideSubstep('substepEbillme');
    Checkout.ShowSubstep('substepCardInfo');
    document.getElementById("uiSubmitBtn").style.display = "inline";
}

/// Check for empty data 
Checkout.CheckEmpty = function(requiredFieldsArray, requiredDataArray, failureField, failureMessage)
{
    var EmptyFound = false
    for (var i = 0; i < requiredDataArray.length; i++)
    {

        if (requiredDataArray[i].length == 0)
        {
            document.getElementById(failureField).innerHTML = failureMessage;
            EmptyFound = true
        }
    }

    if (!EmptyFound) document.getElementById(failureField).innerHTML = "";

    return EmptyFound;
}

Checkout.ValidZip = function(zip, country, failureField)
{
    zip = zip.toUpperCase();
    var regex = /((^\d{5}([- |]\d{4})?$)|(^[A-Z]\d[A-Z][- |]\d[A-Z]\d$))/;
    var Valid = false;
    var CountryLong = ""

    if (country.length > 0)
    {
        switch (country)
        {
            case "US":
                /// 55555
                /// 55555-5555
                if (zip.search(/^\d{5}(-\d{4})?$/) != -1)
                {
                    Valid = true;
                }
                CountryLong = "US";

                break;

            case "CA":
                /// X5X 5X5
                /// X5X-5X5
                /// X5X5X5
                if (zip.search(/^[A-Z]{1}\d{1}[A-Z]{1}[ |-]*\d{1}[A-Z]{1}\d{1}$/) != -1)
                {
                    Valid = true;
                }
                CountryLong = "Canadian";
                break;

            default:
                Valid = true;
                break;
        }

        /// If invalid return the message.
        if (Valid)
        {
            document.getElementById(failureField).innerHTML = "";
        }
        else
        {
            document.getElementById(failureField).innerHTML = "Please enter a valid " + CountryLong + " zip code.";
        }

    }


    return Valid;
}

Checkout.FormHandler = new Safemart.FormHandler("", "", "");

Checkout.UpdatePhone = function(what)
{
    var Phone
    Phone = document.getElementById("txt" + what + "PhoneArea").value;
    Phone += document.getElementById("txt" + what + "PhonePrefix").value;
    Phone += document.getElementById("txt" + what + "PhoneSuffix").value;

    if (what == "Ship")
    {
        Checkout.Customer.Ship.Phone = Phone;
    }
    else if (what == "Bill")
    {
        Checkout.Customer.Bill.Phone = Phone;
    }

}

Checkout.ValidateStepAddress = function()
{

    var Validated = true;

    var FieldCount = 0

    var RequiredFields = new Array();
    RequiredData = new Array();

    RequiredData[FieldCount] = Checkout.Customer.Ship.FirstName;
    RequiredFields[FieldCount++] = "txtShipFirstName";

    RequiredData[FieldCount] = Checkout.Customer.Ship.LastName;
    RequiredFields[FieldCount++] = "txtShipLastName";

    RequiredData[FieldCount] = Checkout.Customer.Ship.AddressLine1;
    RequiredFields[FieldCount++] = "txtShipAddress1";

    RequiredData[FieldCount] = Checkout.Customer.Ship.City;
    RequiredFields[FieldCount++] = "txtShipCity";

    RequiredData[FieldCount] = Checkout.Customer.Ship.Zip;
    RequiredFields[FieldCount++] = "txtShipZipPostalCode";

    if (Checkout.Customer.Ship.Country != "US")
    {
        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            Validated = false;
            document.getElementById("Shipmessage").innerHTML = document.getElementById("SmUsOnlyMessage").innerHTML;
        }

        RequiredData[FieldCount] = Checkout.Customer.Ship.Phone;
        RequiredFields[FieldCount++] = "txtShipPhoneNumber";
    }

    if (!Checkout.Customer.InternalIP)
    {
        RequiredData[FieldCount] = Checkout.Customer.Email;
        RequiredFields[FieldCount++] = "txtCustomerEmail";
    }

    //RequiredFields[6] = Checkout.Customer.Ship.Country;

    if (Checkout.Customer.Ship.Country == "CA")
    {
        RequiredData[FieldCount] = Checkout.Customer.Ship.State;
        RequiredFields[FieldCount++] = "txtShipStateProvince";
    }

    /// Stop checking if invalid data has already been found.
    if (Validated)
    {
        var FailureMessage = "All required fields must be completed."

        if (!Checkout.CheckEmpty(RequiredFields, RequiredData, "Shipmessage", FailureMessage))
        {// all required fields not empty   

            if (!Checkout.ValidZip(Checkout.Customer.Ship.Zip, Checkout.Customer.Ship.Country, "Shipmessage"))
            {// invalid Zip
                Validated = false;
                //document.getElementById("Shipmessage").innerHTML = Checkout.Customer.Bill.InvalidPhoneMsg;
            }

            if (!Checkout.Customer.InternalIP)
            {
                if (!Checkout.Customer.IsEmailValid())
                { /// invalid email
                    Validated = false;
                    document.getElementById("Shipmessage").innerHTML = "Please include a valid email address.";
                }
            }

            /// validate Phone if US
            if (Checkout.Customer.Ship.Country == "US")
            {
                if (!Checkout.Customer.Ship.IsPhoneValid())
                { /// invalid Phone
                    document.getElementById("Shipmessage").innerHTML = Checkout.Customer.Ship.InvalidPhoneMsg;
                    Validated = false;
                }
            }


        }
        else
        {
            Validated = false;
        }
    }
    //document.getElementById("Shipmessage").innerHTML += "  " + Checkout.Customer.Ship.State + "-" + Checkout.Customer.Ship.Country
    if (Validated)
    {
        Checkout.Customer.Ship.GetMethods();

        if (document.getElementById("ShippingOptionsDisclamer") != null)
        {
            if (Checkout.Customer.Ship.Country == "CA")
            {
                document.getElementById("ShippingOptionsDisclamer").style.display = "block";
            }
            else
            {
                document.getElementById("ShippingOptionsDisclamer").style.display = "none";
            }
        }
        var aParameters = new wsi._Parameters();
        aParameters.Add("email", Checkout.Customer.Email);
        wsi._Soap.AddCall("HasAccountCheck", Checkout.Customer.HasAccountCheckReturn, aParameters);

        Checkout.NextStep();
    }
}

Checkout.ValidateStepBillingAddress = function()
{
    //window.status = "ID" +   Checkout.Customer.InternalID();

    var Validated = true;
    //if(!Checkout.Customer.Bill.SameAsShip)
    //{

    var FieldCount = 0

    var RequiredFields = new Array();
    var RequiredData = new Array();

    RequiredData[FieldCount] = Checkout.Customer.Bill.FirstName;
    RequiredFields[FieldCount++] = "txtBillFirstName";

    RequiredData[FieldCount] = Checkout.Customer.Bill.LastName;
    RequiredFields[FieldCount++] = "txtBillLastName";

    RequiredData[FieldCount] = Checkout.Customer.Bill.AddressLine1;
    RequiredFields[FieldCount++] = "txtBillAddress1";

    RequiredData[FieldCount] = Checkout.Customer.Bill.City;
    RequiredFields[FieldCount++] = "txtBillCity";

    RequiredData[FieldCount] = Checkout.Customer.Bill.Zip;
    RequiredFields[FieldCount++] = "txtBillZipPostalCode";

    if (Checkout.Customer.Bill.Country != "US")
    {
        RequiredData[FieldCount] = Checkout.Customer.Bill.Phone;
        RequiredFields[FieldCount++] = "txtBillPhoneNumber";
    }

    if (Checkout.Cart.NoShipping && !Checkout.Customer.InternalIP)
    {
        RequiredData[FieldCount] = Checkout.Customer.Email;
        RequiredFields[FieldCount++] = "txtCustomerBillEmail";
    }

    if (Checkout.Customer.Bill.Country == "CA")
    {
        RequiredData[FieldCount] = Checkout.Customer.Bill.State;
        RequiredFields[FieldCount++] = "txtBillStateProvince";
    }

    var FailureMessage = "All required fields must be completed."

    if (!Checkout.CheckEmpty(RequiredFields, RequiredData, "BillMessage", FailureMessage))
    {

        if (!Checkout.ValidZip(Checkout.Customer.Bill.Zip, Checkout.Customer.Bill.Country, "BillMessage"))
        {// invalid Zip
            document.getElementById("BillMessage").innerHTML = "Please include a valid Zip Code.";
            Validated = false;
        }

        /// validate Phone if US
        if (Checkout.Customer.Bill.Country == "US")
        {
            if (!Checkout.Customer.Bill.IsPhoneValid())
            { /// invalid Phone
                document.getElementById("BillMessage").innerHTML = Checkout.Customer.Bill.InvalidPhoneMsg;
                Validated = false;
            }
        }

        if (Checkout.Cart.NoShipping && !Checkout.Customer.InternalIP)
        {
            if (!Checkout.Customer.IsEmailValid())
            { /// invalid email
                Validated = false;
                document.getElementById("BillMessage").innerHTML = "Please include a valid email address.";
            }
        }
    }
    else
    {
        Validated = false;
    }

    //}

    /// if all fields validate
    if (Validated)
    {
        Checkout.SetTotals();
        Checkout.NextStep();
    }
}

Checkout.ValidateShippingOptions = function()
{
    /// Clear previous values
    Checkout.Customer.Ship.Type = "";
    Checkout.Customer.Ship.Cost = 0;

    // Validate fields

    // if all fields validate

    for (var i = 0; i < document.getElementsByName("ShippingOption").length; i++)
    {
        if (document.getElementsByName("ShippingOption")[i].checked)
        {
            var ShipValue = document.getElementsByName("ShippingOption")[i].value;
            var ShipArray = ShipValue.split("|");
            Checkout.Customer.Ship.Type = ShipArray[0];
            Checkout.Customer.Ship.Cost = parseFloat(ShipArray[1]);
        }
    }
    //alert(Checkout.Customer.Ship.Type.length);

    if (Checkout.Customer.Ship.Type.length == 0)
    {
        document.getElementById("ShipMethodMessage").innerHTML = "Please select a shipping options.";
    }
    else
    {
        Checkout.SetTotals();

        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            document.getElementById("uiSsnLabel").style.display = "block";
            document.getElementById("uiSnn").style.display = "block";
        }

        if (Checkout.eBillme.Enabled() == false)
        {
            document.getElementById("uiBillingMethods-ebillme").style.display = "none";
            document.getElementById("uiEbillmeLogo").style.display = "none";
            document.getElementById("uiEbillmeLink").style.display = "none";
            document.getElementById("uiBillingMethods-cc").style.display = "none";
            Checkout.ShowSubstep('substepCardInfo');
            document.getElementById("uiSubmitBtn").style.display = "inline";
        }
        else
        {
            document.getElementById("uiBillingMethods-ebillme").style.display = "inline";
            document.getElementById("uiEbillmeLogo").style.display = "inline";
            document.getElementById("uiEbillmeLink").style.display = "inline";
            document.getElementById("uiBillingMethods-cc").style.display = "inline";

            //Checkout.HideSubstep("substepCardInfo");
            //Checkout.HideSubstep("substepEbillme");
        }

        if (Checkout.PayPalOrder)
        {
            Checkout.HideSubstep("stepShippingOptions");
            Checkout.ShowStep("stepPayPalConfirmation");
        }
        else
        {
            Checkout.NextStep();
        }
    }
}


Checkout.ShowNoFreeShippingOverlay = function()
{
    YAHOO.example.container.overlay1.cfg.setProperty("context", ["NoFreeShipOverlayLink", "tl", "tr"]);
    YAHOO.example.container.overlay1.setBody(document.getElementById("NoFreeShipOverlay").innerHTML);
    YAHOO.example.container.overlay1.show();
}


Checkout.HideNoFreeShippingOverlay = function()
{
    YAHOO.example.container.overlay1.hide()
}

Checkout.ShowCVV2 = function()
{
    YAHOO.example.container.overlay1.cfg.setProperty("context", ["Whatiscvv2", "tl", "tr"]);
    YAHOO.example.container.overlay1.setBody(document.getElementById("CvvOverlay").innerHTML);
    YAHOO.example.container.overlay1.show();
}


Checkout.HideCVV2 = function()
{
    YAHOO.example.container.overlay1.hide()
}

Checkout.ShowWhySSN = function()
{
    YAHOO.example.container.overlay1.cfg.setProperty("context", ["uiWhySnn", "tl", "tr"]);
    YAHOO.example.container.overlay1.setBody(document.getElementById("WhySnnOverlay").innerHTML);
    YAHOO.example.container.overlay1.show();
}

Checkout.HideWhySSN = function()
{
    YAHOO.example.container.overlay1.hide()
}

Checkout.ValidateCreditCard = function()
{


    if (!Checkout.eBillme.Enabled())
    {
        Checkout.Customer.PaymentMethod("cc");
    }

    if (Checkout.Customer.PaymentMethod() == "")
    {
        document.getElementById("CardMessage").innerHTML = "Please select a payment method.";
    }
    else if (Checkout.Customer.PaymentMethod() == "eBillMe")
    {
        if (Checkout.Customer.Email.length > 0)
        {
            /*
            EbillmePreAuthorize(string sessionId, string customer_Email, string ship_FirstName, string ship_LastName,
            string ship_Company, string ship_AddressLine1, string ship_AddressLine2, string ship_City, string ship_State,
            string ship_Zip, string ship_Country, string ship_Phone, string ship_Type, string ship_Cost, string bill_SameAsShip,
            string bill_FirstName, string bill_LastName, string bill_Company, string bill_AddressLine1, string bill_AddressLine2,
            string bill_City, string bill_State, string bill_Zip, string bill_Country, string bill_Phone, string totalPrice)
            */


            var aParameters = new wsi._Parameters();
            aParameters.Add("sessionId", Safemart.GetSession());
            aParameters.Add("customer_Email", Checkout.Customer.Email);

            aParameters.Add("ship_FirstName", Checkout.Customer.Ship.FirstName);
            aParameters.Add("ship_LastName", Checkout.Customer.Ship.LastName);
            aParameters.Add("ship_Company", Checkout.Customer.Ship.Company);
            aParameters.Add("ship_AddressLine1", Checkout.Customer.Ship.AddressLine1);
            aParameters.Add("ship_AddressLine2", Checkout.Customer.Ship.AddressLine2);
            aParameters.Add("ship_City", Checkout.Customer.Ship.City);
            aParameters.Add("ship_State", Checkout.Customer.Ship.State);
            aParameters.Add("ship_Zip", Checkout.Customer.Ship.Zip);
            aParameters.Add("ship_Country", Checkout.Customer.Ship.Country);
            aParameters.Add("ship_Phone", Checkout.Customer.Ship.Phone);
            aParameters.Add("ship_Type", Checkout.Customer.Ship.Type);
            aParameters.Add("ship_Cost", Checkout.Customer.Ship.Cost);
            aParameters.Add("bill_SameAsShip", (Checkout.Customer.Bill.SameAsShip ? "true" : "false"));
            aParameters.Add("bill_FirstName", Checkout.Customer.Bill.FirstName);
            aParameters.Add("bill_LastName", Checkout.Customer.Bill.LastName);
            aParameters.Add("bill_Company", Checkout.Customer.Bill.Company);
            aParameters.Add("bill_AddressLine1", Checkout.Customer.Bill.AddressLine1);
            aParameters.Add("bill_AddressLine2", Checkout.Customer.Bill.AddressLine2);
            aParameters.Add("bill_City", Checkout.Customer.Bill.City);
            aParameters.Add("bill_State", Checkout.Customer.Bill.State);
            aParameters.Add("bill_Zip", Checkout.Customer.Bill.Zip);
            aParameters.Add("bill_Country", Checkout.Customer.Bill.Country);
            aParameters.Add("bill_Phone", Checkout.Customer.Bill.Phone);
            aParameters.Add("totalPrice", Checkout.RoundMoney(Checkout.Cart.Total));

            wsi._Soap.AddCall("PreAuthorize_eBillme", Checkout.eBillme.PreAuthorizeReturn, aParameters);
        }
        else
        {
            alert("An email address is required to use the eBillme option.");
        }
    }
    else
    {
        var RequiredFields = new Array();
        RequiredFields[0] = "txtFirstNameOnCard";
        RequiredFields[1] = "txtCardNumber";
        RequiredFields[2] = "intMonth";
        RequiredFields[3] = "intYear";
        //RequiredFields[4] = "txtCWCode";

        RequiredData = new Array();
        RequiredData[0] = Checkout.Customer.CreditCard.NameOnCard;
        RequiredData[1] = Checkout.Customer.CreditCard.Number;
        RequiredData[2] = Checkout.Customer.CreditCard.ExpirationMonth;
        RequiredData[3] = Checkout.Customer.CreditCard.ExpirationYear;
        RequiredData[4] = Checkout.Customer.CreditCard.CVV2;

        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            RequiredData[5] = Checkout.Customer.SSN;
        }

        var FailureMessage = "All required fields must be completed."

        if (!Checkout.CheckEmpty(RequiredFields, RequiredData, "CardMessage", FailureMessage))
        {
            var PasswordGood = (Checkout.Customer.Password == Checkout.Customer.PassConfirm ? true : false)
            var SsnGood = (!Checkout.Cart.ContainsSmartMoneyPackage || Checkout.Customer.IsSsnValid() ? true : false)

            if (!SsnGood)
            { /// Invalid SSN
                document.getElementById("CardMessage").innerHTML = "Invalid Social security number. Please re-type your SSN.";
            }
            else if (Checkout.Customer.InternalID().length == 0 && !PasswordGood)
            { /// The password and the confirmed password do not match.
                /// Customers who are logged in are not prompted to create an account

                document.getElementById("CardMessage").innerHTML = "Your Password Confirmation is different than your Password. Please re-type your Password.";
                document.getElementById("txtAccountPassword").value = "";
                document.getElementById("txtAccountPassConfirm").value = "";

                Checkout.Customer.Password = "";
                Checkout.Customer.PassConfirm = "";


            }
            else
            { /// Passed validation
                Checkout.PlaceOrder();
            }
        }
    }
}


Checkout.ValidateQty = function(what, checkBlank)
{
    if (typeof (checkBlank) == "undefined") checkBlank = false;

    var MainProductQty = what.value;
    if (MainProductQty.match(/[^0-9]/))
    {
        /// Strip all non numeric characters
        what.value = MainProductQty.replace(/[^0-9]/g, "");
    }

    /// Don't allow 0 Qty
    if (MainProductQty == "0")
    {
        what.value = "1";
    }

    if (checkBlank)
    {
        if (what.value.length == 0)
        {
            what.value = what.getAttribute("defaultvalue");
        }
    }
}

// The following functions could be used globally

function ClearInputExample(who)
{
    if (who.style.fontStyle == 'italic')
    {
        who.value = '';
        who.style.color = 'black';
        who.style.fontStyle = 'normal';
    }
}


var CartProcessor = function()
{

    /// Cart Items are saved in this format
    /// <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>

    /// <summary>
    /// Add a Product to the Cart
    /// </summary>
    /// <param name="item">The product to be added</param>
    this.AddToCart = function(item)
    {
        /// Get the current cart
        var CartData = this.GetCart();

        /// If the cart is not empty add a delimiter
        if (CartData.length > 0)
        {
            CartData += "||";
        }

        /// Add the item to the cart
        CartData += item;

        /// Save the cart
        SaveCart(CartData);

        /// Return the cart
        return CartData;
    }

    /// <summary>
    /// Update the Qty for a Product
    /// </summary>
    /// <param name="groupId">The Group Id for the product to be updated</param>
    /// <param name="qty">The new Quantity</param>
    /// <returns>The Cart Data</returns>
    this.UpdateQty = function(groupId, qty)
    {
        /// Get the current cart
        var CartData = this.GetCart();

        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");

            /// To hold the array position of the main item
            var FoundMain = null;
            var BaseQty = null;

            /// Search for the Main item
            for (var i = 0; i < ItemArray.length; ++i)
            {
                /// Split the Item
                var ItemProperties = ItemArray[i].split("|");

                if (ItemProperties[0] == groupId && ItemProperties[1] == "0")
                {
                    /// Store the Main item
                    FoundMain = i
                    BaseQty = ItemProperties[4];
                    break;
                }
            }

            if (FoundMain != null)
            {
                if (qty.length > 0)
                {

                    for (var i = 0; i < ItemArray.length; ++i)
                    {
                        /// Split the Item
                        var ItemProperties = ItemArray[i].split("|");

                        if (ItemProperties[0] == groupId)
                        {
                            /// Get the new Qty
                            var NewQty = null;
                            if (ItemProperties[1] == "0")
                            {
                                NewQty = qty;
                            }
                            else
                            {
                                NewQty = (ItemProperties[4] / BaseQty) * qty;
                            }

                            /// Update the Qty
                            ItemProperties[4] = NewQty;

                            /// Push the update back into the array.
                            ItemArray[i] = ItemProperties.join("|");

                            /// Save the cart
                            CartData = ItemArray.join("||")
                            SaveCart(CartData);
                        }
                    }
                }
                else
                {
                    /// Remove zero Qty items
                    CartData = RemoveFromCart(groupId);
                }
            }
        }

        return CartData;
    }

    /// <summary>
    /// Get the Sub-Total of all items in the cart. Addons are included in the Sub-Total.
    /// </summary>
    this.CartTotal = function()
    {
        /// Get the current cart
        var CartData = this.GetCart();

        var Total = 0;

        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");

            /// Get the Cart Total

            for (var iItems = 0; iItems < ItemArray.length; ++iItems)
            {
                /// Split the Item
                var ItemProperties = ItemArray[iItems].split("|");

                var Qty = ItemProperties[4]
                var UnitPrice = ItemProperties[5]

                /// Add Item price to total
                Total += parseFloat(UnitPrice) * parseInt(Qty);

            }
        }

        /// Convert the total to money
        Total = SWH.ToMoney(Total, false);

        /// String the 
        /// Return the total
        return Total;

    }

    /// <summary>
    /// Get the number of items in the cart. Addons are excluded from the count
    /// </summary>
    this.CartQty = function()
    {
        /// Get the current cart
        var CartData = this.GetCart();
        var Qty = 0;

        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");

            /// Get the Cart Qty
            for (var iItems = 0; iItems < ItemArray.length; ++iItems)
            {
                /// Split the Item
                var ItemProperties = ItemArray[iItems].split("|");

                /// Do not include Addons in the Qty count
                if (ItemProperties[1] == 0)
                {
                    Qty += parseInt(ItemProperties[4]);
                }
            }
        }
        /// Return the Qty
        return Qty;
    }

    /// <summary>
    /// Get a comma deliminted list of Id
    /// </summary>
    this.GetIdList = function()
    {

    }

    /// <summary>
    /// Remove a Product from the cart.
    /// </summary>
    /// <param name="groupId">The Group Id for the product to be removed</param>
    this.RemoveFromCart = function(groupId)
    {
        /// Get the current cart
        var CartData = this.GetCart();

        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");

            /// Search for items in reverse order.
            for (var i = ItemArray.length - 1; i <= 0; --i)
            {
                /// Split the Item
                var ItemProperties = ItemArray[i].split("|");

                if (ItemProperties[0] == groupId)
                {
                    ItemArray.splice(Found, 1);
                }
            }


            if (ItemArray.length == 0)
            {
                /// Empty cart
                this.ClearCart();
            }
            else
            {
                CartData = ItemArray.join("||")
                SaveCart(CartData);
            }
        }

        return CartData;
    }

    /// <summary>
    /// Remove all Products from the Cart.
    /// </summary>
    this.ClearCart = function()
    {
        SaveCart("");
    }

    /// <summary>
    /// Get all the Products from the Cart.
    /// </summary>
    this.GetCart = function()
    {
        var CartData = (wsi._Cookie.GetCrumb("cart") == null ? "" : wsi._Cookie.GetCrumb("cart"));
        //alert("GetCart\r\n\r\n"+CartData);
        return CartData
    }

    /// <summary>
    /// Commit the Cart to Cookies. The previous value will be over-writen.
    /// </summary>
    /// <param name="cartData">The new Cart</param>
    var SaveCart = function(cartData)
    {
        wsi._Cookie.SaveCrumb("cart", cartData);
    }
}

if (Checkout.Cart.Mode == "Cookie")
{
    Checkout.CartProcessor = new CartProcessor();
}
else
{
    Checkout.CartProcessor = null;
}

/******************************************
*                                         *
*             End Checkout                *
*                                         *
*                                         *
*******************************************/



/******************************************
*                                         *
*             3rd party code              *
*                                         *
*                                         *
*******************************************/


/******************************************************************************
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.3.1
******************************************************************************/
// YUI version 2.3.1: /build/yahoo-dom-event/yahoo-dom-event.js
if (typeof YAHOO == "undefined") { var YAHOO = {}; } YAHOO.namespace = function () { var A = arguments, E = null, C, B, D; for (C = 0; C < A.length; C = C + 1) { D = A[C].split("."); E = YAHOO; for (B = (D[0] == "YAHOO") ? 1 : 0; B < D.length; B = B + 1) { E[D[B]] = E[D[B]] || {}; E = E[D[B]]; } } return E; }; YAHOO.log = function (D, A, C) { var B = YAHOO.widget.Logger; if (B && B.log) { return B.log(D, A, C); } else { return false; } }; YAHOO.register = function (A, E, D) { var I = YAHOO.env.modules; if (!I[A]) { I[A] = { versions: [], builds: [] }; } var B = I[A], H = D.version, G = D.build, F = YAHOO.env.listeners; B.name = A; B.version = H; B.build = G; B.versions.push(H); B.builds.push(G); B.mainClass = E; for (var C = 0; C < F.length; C = C + 1) { F[C](B); } if (E) { E.VERSION = H; E.BUILD = G; } else { YAHOO.log("mainClass is undefined for module " + A, "warn"); } }; YAHOO.env = YAHOO.env || { modules: [], listeners: [] }; YAHOO.env.getVersion = function (A) { return YAHOO.env.modules[A] || null; }; YAHOO.env.ua = function () { var C = { ie: 0, opera: 0, gecko: 0, webkit: 0 }; var B = navigator.userAgent, A; if ((/KHTML/).test(B)) { C.webkit = 1; } A = B.match(/AppleWebKit\/([^\s]*)/); if (A && A[1]) { C.webkit = parseFloat(A[1]); } if (!C.webkit) { A = B.match(/Opera[\s\/]([^\s]*)/); if (A && A[1]) { C.opera = parseFloat(A[1]); } else { A = B.match(/MSIE\s([^;]*)/); if (A && A[1]) { C.ie = parseFloat(A[1]); } else { A = B.match(/Gecko\/([^\s]*)/); if (A) { C.gecko = 1; A = B.match(/rv:([^\s\)]*)/); if (A && A[1]) { C.gecko = parseFloat(A[1]); } } } } } return C; } (); (function () { YAHOO.namespace("util", "widget", "example"); if ("undefined" !== typeof YAHOO_config) { var B = YAHOO_config.listener, A = YAHOO.env.listeners, D = true, C; if (B) { for (C = 0; C < A.length; C = C + 1) { if (A[C] == B) { D = false; break; } } if (D) { A.push(B); } } } })(); YAHOO.lang = { isArray: function (B) { if (B) { var A = YAHOO.lang; return A.isNumber(B.length) && A.isFunction(B.splice) && !A.hasOwnProperty(B.length); } return false; }, isBoolean: function (A) { return typeof A === "boolean"; }, isFunction: function (A) { return typeof A === "function"; }, isNull: function (A) { return A === null; }, isNumber: function (A) { return typeof A === "number" && isFinite(A); }, isObject: function (A) { return (A && (typeof A === "object" || YAHOO.lang.isFunction(A))) || false; }, isString: function (A) { return typeof A === "string"; }, isUndefined: function (A) { return typeof A === "undefined"; }, hasOwnProperty: function (A, B) { if (Object.prototype.hasOwnProperty) { return A.hasOwnProperty(B); } return !YAHOO.lang.isUndefined(A[B]) && A.constructor.prototype[B] !== A[B]; }, _IEEnumFix: function (C, B) { if (YAHOO.env.ua.ie) { var E = ["toString", "valueOf"], A; for (A = 0; A < E.length; A = A + 1) { var F = E[A], D = B[F]; if (YAHOO.lang.isFunction(D) && D != Object.prototype[F]) { C[F] = D; } } } }, extend: function (D, E, C) { if (!E || !D) { throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included."); } var B = function () { }; B.prototype = E.prototype; D.prototype = new B(); D.prototype.constructor = D; D.superclass = E.prototype; if (E.prototype.constructor == Object.prototype.constructor) { E.prototype.constructor = E; } if (C) { for (var A in C) { D.prototype[A] = C[A]; } YAHOO.lang._IEEnumFix(D.prototype, C); } }, augmentObject: function (E, D) { if (!D || !E) { throw new Error("Absorb failed, verify dependencies."); } var A = arguments, C, F, B = A[2]; if (B && B !== true) { for (C = 2; C < A.length; C = C + 1) { E[A[C]] = D[A[C]]; } } else { for (F in D) { if (B || !E[F]) { E[F] = D[F]; } } YAHOO.lang._IEEnumFix(E, D); } }, augmentProto: function (D, C) { if (!C || !D) { throw new Error("Augment failed, verify dependencies."); } var A = [D.prototype, C.prototype]; for (var B = 2; B < arguments.length; B = B + 1) { A.push(arguments[B]); } YAHOO.lang.augmentObject.apply(this, A); }, dump: function (A, G) { var C = YAHOO.lang, D, F, I = [], J = "{...}", B = "f(){...}", H = ", ", E = " => "; if (!C.isObject(A)) { return A + ""; } else { if (A instanceof Date || ("nodeType" in A && "tagName" in A)) { return A; } else { if (C.isFunction(A)) { return B; } } } G = (C.isNumber(G)) ? G : 3; if (C.isArray(A)) { I.push("["); for (D = 0, F = A.length; D < F; D = D + 1) { if (C.isObject(A[D])) { I.push((G > 0) ? C.dump(A[D], G - 1) : J); } else { I.push(A[D]); } I.push(H); } if (I.length > 1) { I.pop(); } I.push("]"); } else { I.push("{"); for (D in A) { if (C.hasOwnProperty(A, D)) { I.push(D + E); if (C.isObject(A[D])) { I.push((G > 0) ? C.dump(A[D], G - 1) : J); } else { I.push(A[D]); } I.push(H); } } if (I.length > 1) { I.pop(); } I.push("}"); } return I.join(""); }, substitute: function (Q, B, J) { var G, F, E, M, N, P, D = YAHOO.lang, L = [], C, H = "dump", K = " ", A = "{", O = "}"; for (; ; ) { G = Q.lastIndexOf(A); if (G < 0) { break; } F = Q.indexOf(O, G); if (G + 1 >= F) { break; } C = Q.substring(G + 1, F); M = C; P = null; E = M.indexOf(K); if (E > -1) { P = M.substring(E + 1); M = M.substring(0, E); } N = B[M]; if (J) { N = J(M, N, P); } if (D.isObject(N)) { if (D.isArray(N)) { N = D.dump(N, parseInt(P, 10)); } else { P = P || ""; var I = P.indexOf(H); if (I > -1) { P = P.substring(4); } if (N.toString === Object.prototype.toString || I > -1) { N = D.dump(N, parseInt(P, 10)); } else { N = N.toString(); } } } else { if (!D.isString(N) && !D.isNumber(N)) { N = "~-" + L.length + "-~"; L[L.length] = C; } } Q = Q.substring(0, G) + N + Q.substring(F + 1); } for (G = L.length - 1; G >= 0; G = G - 1) { Q = Q.replace(new RegExp("~-" + G + "-~"), "{" + L[G] + "}", "g"); } return Q; }, trim: function (A) { try { return A.replace(/^\s+|\s+$/g, ""); } catch (B) { return A; } }, merge: function () { var C = {}, A = arguments, B; for (B = 0; B < A.length; B = B + 1) { YAHOO.lang.augmentObject(C, A[B], true); } return C; }, isValue: function (B) { var A = YAHOO.lang; return (A.isObject(B) || A.isString(B) || A.isNumber(B) || A.isBoolean(B)); } }; YAHOO.util.Lang = YAHOO.lang; YAHOO.lang.augment = YAHOO.lang.augmentProto; YAHOO.augment = YAHOO.lang.augmentProto; YAHOO.extend = YAHOO.lang.extend; YAHOO.register("yahoo", YAHOO, { version: "2.3.1", build: "541" }); (function () { var B = YAHOO.util, K, I, H = 0, J = {}, F = {}; var C = YAHOO.env.ua.opera, L = YAHOO.env.ua.webkit, A = YAHOO.env.ua.gecko, G = YAHOO.env.ua.ie; var E = { HYPHEN: /(-[a-z])/i, ROOT_TAG: /^body|html$/i }; var M = function (O) { if (!E.HYPHEN.test(O)) { return O; } if (J[O]) { return J[O]; } var P = O; while (E.HYPHEN.exec(P)) { P = P.replace(RegExp.$1, RegExp.$1.substr(1).toUpperCase()); } J[O] = P; return P; }; var N = function (P) { var O = F[P]; if (!O) { O = new RegExp("(?:^|\\s+)" + P + "(?:\\s+|$)"); F[P] = O; } return O; }; if (document.defaultView && document.defaultView.getComputedStyle) { K = function (O, R) { var Q = null; if (R == "float") { R = "cssFloat"; } var P = document.defaultView.getComputedStyle(O, ""); if (P) { Q = P[M(R)]; } return O.style[R] || Q; }; } else { if (document.documentElement.currentStyle && G) { K = function (O, Q) { switch (M(Q)) { case "opacity": var S = 100; try { S = O.filters["DXImageTransform.Microsoft.Alpha"].opacity; } catch (R) { try { S = O.filters("alpha").opacity; } catch (R) { } } return S / 100; case "float": Q = "styleFloat"; default: var P = O.currentStyle ? O.currentStyle[Q] : null; return (O.style[Q] || P); } }; } else { K = function (O, P) { return O.style[P]; }; } } if (G) { I = function (O, P, Q) { switch (P) { case "opacity": if (YAHOO.lang.isString(O.style.filter)) { O.style.filter = "alpha(opacity=" + Q * 100 + ")"; if (!O.currentStyle || !O.currentStyle.hasLayout) { O.style.zoom = 1; } } break; case "float": P = "styleFloat"; default: O.style[P] = Q; } }; } else { I = function (O, P, Q) { if (P == "float") { P = "cssFloat"; } O.style[P] = Q; }; } var D = function (O, P) { return O && O.nodeType == 1 && (!P || P(O)); }; YAHOO.util.Dom = { get: function (Q) { if (Q && (Q.tagName || Q.item)) { return Q; } if (YAHOO.lang.isString(Q) || !Q) { return document.getElementById(Q); } if (Q.length !== undefined) { var R = []; for (var P = 0, O = Q.length; P < O; ++P) { R[R.length] = B.Dom.get(Q[P]); } return R; } return Q; }, getStyle: function (O, Q) { Q = M(Q); var P = function (R) { return K(R, Q); }; return B.Dom.batch(O, P, B.Dom, true); }, setStyle: function (O, Q, R) { Q = M(Q); var P = function (S) { I(S, Q, R); }; B.Dom.batch(O, P, B.Dom, true); }, getXY: function (O) { var P = function (R) { if ((R.parentNode === null || R.offsetParent === null || this.getStyle(R, "display") == "none") && R != document.body) { return false; } var Q = null; var V = []; var S; var T = R.ownerDocument; if (R.getBoundingClientRect) { S = R.getBoundingClientRect(); return [S.left + B.Dom.getDocumentScrollLeft(R.ownerDocument), S.top + B.Dom.getDocumentScrollTop(R.ownerDocument)]; } else { V = [R.offsetLeft, R.offsetTop]; Q = R.offsetParent; var U = this.getStyle(R, "position") == "absolute"; if (Q != R) { while (Q) { V[0] += Q.offsetLeft; V[1] += Q.offsetTop; if (L && !U && this.getStyle(Q, "position") == "absolute") { U = true; } Q = Q.offsetParent; } } if (L && U) { V[0] -= R.ownerDocument.body.offsetLeft; V[1] -= R.ownerDocument.body.offsetTop; } } Q = R.parentNode; while (Q.tagName && !E.ROOT_TAG.test(Q.tagName)) { if (B.Dom.getStyle(Q, "display").search(/^inline|table-row.*$/i)) { V[0] -= Q.scrollLeft; V[1] -= Q.scrollTop; } Q = Q.parentNode; } return V; }; return B.Dom.batch(O, P, B.Dom, true); }, getX: function (O) { var P = function (Q) { return B.Dom.getXY(Q)[0]; }; return B.Dom.batch(O, P, B.Dom, true); }, getY: function (O) { var P = function (Q) { return B.Dom.getXY(Q)[1]; }; return B.Dom.batch(O, P, B.Dom, true); }, setXY: function (O, R, Q) { var P = function (U) { var T = this.getStyle(U, "position"); if (T == "static") { this.setStyle(U, "position", "relative"); T = "relative"; } var W = this.getXY(U); if (W === false) { return false; } var V = [parseInt(this.getStyle(U, "left"), 10), parseInt(this.getStyle(U, "top"), 10)]; if (isNaN(V[0])) { V[0] = (T == "relative") ? 0 : U.offsetLeft; } if (isNaN(V[1])) { V[1] = (T == "relative") ? 0 : U.offsetTop; } if (R[0] !== null) { U.style.left = R[0] - W[0] + V[0] + "px"; } if (R[1] !== null) { U.style.top = R[1] - W[1] + V[1] + "px"; } if (!Q) { var S = this.getXY(U); if ((R[0] !== null && S[0] != R[0]) || (R[1] !== null && S[1] != R[1])) { this.setXY(U, R, true); } } }; B.Dom.batch(O, P, B.Dom, true); }, setX: function (P, O) { B.Dom.setXY(P, [O, null]); }, setY: function (O, P) { B.Dom.setXY(O, [null, P]); }, getRegion: function (O) { var P = function (Q) { if ((Q.parentNode === null || Q.offsetParent === null || this.getStyle(Q, "display") == "none") && Q != document.body) { return false; } var R = B.Region.getRegion(Q); return R; }; return B.Dom.batch(O, P, B.Dom, true); }, getClientWidth: function () { return B.Dom.getViewportWidth(); }, getClientHeight: function () { return B.Dom.getViewportHeight(); }, getElementsByClassName: function (S, W, T, U) { W = W || "*"; T = (T) ? B.Dom.get(T) : null || document; if (!T) { return []; } var P = [], O = T.getElementsByTagName(W), V = N(S); for (var Q = 0, R = O.length; Q < R; ++Q) { if (V.test(O[Q].className)) { P[P.length] = O[Q]; if (U) { U.call(O[Q], O[Q]); } } } return P; }, hasClass: function (Q, P) { var O = N(P); var R = function (S) { return O.test(S.className); }; return B.Dom.batch(Q, R, B.Dom, true); }, addClass: function (P, O) { var Q = function (R) { if (this.hasClass(R, O)) { return false; } R.className = YAHOO.lang.trim([R.className, O].join(" ")); return true; }; return B.Dom.batch(P, Q, B.Dom, true); }, removeClass: function (Q, P) { var O = N(P); var R = function (S) { if (!this.hasClass(S, P)) { return false; } var T = S.className; S.className = T.replace(O, " "); if (this.hasClass(S, P)) { this.removeClass(S, P); } S.className = YAHOO.lang.trim(S.className); return true; }; return B.Dom.batch(Q, R, B.Dom, true); }, replaceClass: function (R, P, O) { if (!O || P === O) { return false; } var Q = N(P); var S = function (T) { if (!this.hasClass(T, P)) { this.addClass(T, O); return true; } T.className = T.className.replace(Q, " " + O + " "); if (this.hasClass(T, P)) { this.replaceClass(T, P, O); } T.className = YAHOO.lang.trim(T.className); return true; }; return B.Dom.batch(R, S, B.Dom, true); }, generateId: function (O, Q) { Q = Q || "yui-gen"; var P = function (R) { if (R && R.id) { return R.id; } var S = Q + H++; if (R) { R.id = S; } return S; }; return B.Dom.batch(O, P, B.Dom, true) || P.apply(B.Dom, arguments); }, isAncestor: function (P, Q) { P = B.Dom.get(P); if (!P || !Q) { return false; } var O = function (R) { if (P.contains && R.nodeType && !L) { return P.contains(R); } else { if (P.compareDocumentPosition && R.nodeType) { return !!(P.compareDocumentPosition(R) & 16); } else { if (R.nodeType) { return !!this.getAncestorBy(R, function (S) { return S == P; }); } } } return false; }; return B.Dom.batch(Q, O, B.Dom, true); }, inDocument: function (O) { var P = function (Q) { if (L) { while (Q = Q.parentNode) { if (Q == document.documentElement) { return true; } } return false; } return this.isAncestor(document.documentElement, Q); }; return B.Dom.batch(O, P, B.Dom, true); }, getElementsBy: function (V, P, Q, S) { P = P || "*"; Q = (Q) ? B.Dom.get(Q) : null || document; if (!Q) { return []; } var R = [], U = Q.getElementsByTagName(P); for (var T = 0, O = U.length; T < O; ++T) { if (V(U[T])) { R[R.length] = U[T]; if (S) { S(U[T]); } } } return R; }, batch: function (S, V, U, Q) { S = (S && (S.tagName || S.item)) ? S : B.Dom.get(S); if (!S || !V) { return false; } var R = (Q) ? U : window; if (S.tagName || S.length === undefined) { return V.call(R, S, U); } var T = []; for (var P = 0, O = S.length; P < O; ++P) { T[T.length] = V.call(R, S[P], U); } return T; }, getDocumentHeight: function () { var P = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight; var O = Math.max(P, B.Dom.getViewportHeight()); return O; }, getDocumentWidth: function () { var P = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth; var O = Math.max(P, B.Dom.getViewportWidth()); return O; }, getViewportHeight: function () { var O = self.innerHeight; var P = document.compatMode; if ((P || G) && !C) { O = (P == "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; } return O; }, getViewportWidth: function () { var O = self.innerWidth; var P = document.compatMode; if (P || G) { O = (P == "CSS1Compat") ? document.documentElement.clientWidth : document.body.clientWidth; } return O; }, getAncestorBy: function (O, P) { while (O = O.parentNode) { if (D(O, P)) { return O; } } return null; }, getAncestorByClassName: function (P, O) { P = B.Dom.get(P); if (!P) { return null; } var Q = function (R) { return B.Dom.hasClass(R, O); }; return B.Dom.getAncestorBy(P, Q); }, getAncestorByTagName: function (P, O) { P = B.Dom.get(P); if (!P) { return null; } var Q = function (R) { return R.tagName && R.tagName.toUpperCase() == O.toUpperCase(); }; return B.Dom.getAncestorBy(P, Q); }, getPreviousSiblingBy: function (O, P) { while (O) { O = O.previousSibling; if (D(O, P)) { return O; } } return null; }, getPreviousSibling: function (O) { O = B.Dom.get(O); if (!O) { return null; } return B.Dom.getPreviousSiblingBy(O); }, getNextSiblingBy: function (O, P) { while (O) { O = O.nextSibling; if (D(O, P)) { return O; } } return null; }, getNextSibling: function (O) { O = B.Dom.get(O); if (!O) { return null; } return B.Dom.getNextSiblingBy(O); }, getFirstChildBy: function (O, Q) { var P = (D(O.firstChild, Q)) ? O.firstChild : null; return P || B.Dom.getNextSiblingBy(O.firstChild, Q); }, getFirstChild: function (O, P) { O = B.Dom.get(O); if (!O) { return null; } return B.Dom.getFirstChildBy(O); }, getLastChildBy: function (O, Q) { if (!O) { return null; } var P = (D(O.lastChild, Q)) ? O.lastChild : null; return P || B.Dom.getPreviousSiblingBy(O.lastChild, Q); }, getLastChild: function (O) { O = B.Dom.get(O); return B.Dom.getLastChildBy(O); }, getChildrenBy: function (P, R) { var Q = B.Dom.getFirstChildBy(P, R); var O = Q ? [Q] : []; B.Dom.getNextSiblingBy(Q, function (S) { if (!R || R(S)) { O[O.length] = S; } return false; }); return O; }, getChildren: function (O) { O = B.Dom.get(O); if (!O) { } return B.Dom.getChildrenBy(O); }, getDocumentScrollLeft: function (O) { O = O || document; return Math.max(O.documentElement.scrollLeft, O.body.scrollLeft); }, getDocumentScrollTop: function (O) { O = O || document; return Math.max(O.documentElement.scrollTop, O.body.scrollTop); }, insertBefore: function (P, O) { P = B.Dom.get(P); O = B.Dom.get(O); if (!P || !O || !O.parentNode) { return null; } return O.parentNode.insertBefore(P, O); }, insertAfter: function (P, O) { P = B.Dom.get(P); O = B.Dom.get(O); if (!P || !O || !O.parentNode) { return null; } if (O.nextSibling) { return O.parentNode.insertBefore(P, O.nextSibling); } else { return O.parentNode.appendChild(P); } } }; })(); YAHOO.util.Region = function (C, D, A, B) { this.top = C; this[1] = C; this.right = D; this.bottom = A; this.left = B; this[0] = B; }; YAHOO.util.Region.prototype.contains = function (A) { return (A.left >= this.left && A.right <= this.right && A.top >= this.top && A.bottom <= this.bottom); }; YAHOO.util.Region.prototype.getArea = function () { return ((this.bottom - this.top) * (this.right - this.left)); }; YAHOO.util.Region.prototype.intersect = function (E) { var C = Math.max(this.top, E.top); var D = Math.min(this.right, E.right); var A = Math.min(this.bottom, E.bottom); var B = Math.max(this.left, E.left); if (A >= C && D >= B) { return new YAHOO.util.Region(C, D, A, B); } else { return null; } }; YAHOO.util.Region.prototype.union = function (E) { var C = Math.min(this.top, E.top); var D = Math.max(this.right, E.right); var A = Math.max(this.bottom, E.bottom); var B = Math.min(this.left, E.left); return new YAHOO.util.Region(C, D, A, B); }; YAHOO.util.Region.prototype.toString = function () { return ("Region {top: " + this.top + ", right: " + this.right + ", bottom: " + this.bottom + ", left: " + this.left + "}"); }; YAHOO.util.Region.getRegion = function (D) { var F = YAHOO.util.Dom.getXY(D); var C = F[1]; var E = F[0] + D.offsetWidth; var A = F[1] + D.offsetHeight; var B = F[0]; return new YAHOO.util.Region(C, E, A, B); }; YAHOO.util.Point = function (A, B) { if (YAHOO.lang.isArray(A)) { B = A[1]; A = A[0]; } this.x = this.right = this.left = this[0] = A; this.y = this.top = this.bottom = this[1] = B; }; YAHOO.util.Point.prototype = new YAHOO.util.Region(); YAHOO.register("dom", YAHOO.util.Dom, { version: "2.3.1", build: "541" }); YAHOO.util.CustomEvent = function (D, B, C, A) { this.type = D; this.scope = B || window; this.silent = C; this.signature = A || YAHOO.util.CustomEvent.LIST; this.subscribers = []; if (!this.silent) { } var E = "_YUICEOnSubscribe"; if (D !== E) { this.subscribeEvent = new YAHOO.util.CustomEvent(E, this, true); } this.lastError = null; }; YAHOO.util.CustomEvent.LIST = 0; YAHOO.util.CustomEvent.FLAT = 1; YAHOO.util.CustomEvent.prototype = { subscribe: function (B, C, A) { if (!B) { throw new Error("Invalid callback for subscriber to '" + this.type + "'"); } if (this.subscribeEvent) { this.subscribeEvent.fire(B, C, A); } this.subscribers.push(new YAHOO.util.Subscriber(B, C, A)); }, unsubscribe: function (D, F) { if (!D) { return this.unsubscribeAll(); } var E = false; for (var B = 0, A = this.subscribers.length; B < A; ++B) { var C = this.subscribers[B]; if (C && C.contains(D, F)) { this._delete(B); E = true; } } return E; }, fire: function () { var E = this.subscribers.length; if (!E && this.silent) { return true; } var H = [], G = true, D, I = false; for (D = 0; D < arguments.length; ++D) { H.push(arguments[D]); } var A = H.length; if (!this.silent) { } for (D = 0; D < E; ++D) { var L = this.subscribers[D]; if (!L) { I = true; } else { if (!this.silent) { } var K = L.getScope(this.scope); if (this.signature == YAHOO.util.CustomEvent.FLAT) { var B = null; if (H.length > 0) { B = H[0]; } try { G = L.fn.call(K, B, L.obj); } catch (F) { this.lastError = F; } } else { try { G = L.fn.call(K, this.type, H, L.obj); } catch (F) { this.lastError = F; } } if (false === G) { if (!this.silent) { } return false; } } } if (I) { var J = [], C = this.subscribers; for (D = 0, E = C.length; D < E; D = D + 1) { J.push(C[D]); } this.subscribers = J; } return true; }, unsubscribeAll: function () { for (var B = 0, A = this.subscribers.length; B < A; ++B) { this._delete(A - 1 - B); } this.subscribers = []; return B; }, _delete: function (A) { var B = this.subscribers[A]; if (B) { delete B.fn; delete B.obj; } this.subscribers[A] = null; }, toString: function () { return "CustomEvent: '" + this.type + "', scope: " + this.scope; } }; YAHOO.util.Subscriber = function (B, C, A) { this.fn = B; this.obj = YAHOO.lang.isUndefined(C) ? null : C; this.override = A; }; YAHOO.util.Subscriber.prototype.getScope = function (A) { if (this.override) { if (this.override === true) { return this.obj; } else { return this.override; } } return A; }; YAHOO.util.Subscriber.prototype.contains = function (A, B) { if (B) { return (this.fn == A && this.obj == B); } else { return (this.fn == A); } }; YAHOO.util.Subscriber.prototype.toString = function () { return "Subscriber { obj: " + this.obj + ", override: " + (this.override || "no") + " }"; }; if (!YAHOO.util.Event) { YAHOO.util.Event = function () { var H = false; var J = false; var I = []; var K = []; var G = []; var E = []; var C = 0; var F = []; var B = []; var A = 0; var D = { 63232: 38, 63233: 40, 63234: 37, 63235: 39 }; return { POLL_RETRYS: 4000, POLL_INTERVAL: 10, EL: 0, TYPE: 1, FN: 2, WFN: 3, UNLOAD_OBJ: 3, ADJ_SCOPE: 4, OBJ: 5, OVERRIDE: 6, lastError: null, isSafari: YAHOO.env.ua.webkit, webkit: YAHOO.env.ua.webkit, isIE: YAHOO.env.ua.ie, _interval: null, startInterval: function () { if (!this._interval) { var L = this; var M = function () { L._tryPreloadAttach(); }; this._interval = setInterval(M, this.POLL_INTERVAL); } }, onAvailable: function (N, L, O, M) { F.push({ id: N, fn: L, obj: O, override: M, checkReady: false }); C = this.POLL_RETRYS; this.startInterval(); }, onDOMReady: function (L, N, M) { if (J) { setTimeout(function () { var O = window; if (M) { if (M === true) { O = N; } else { O = M; } } L.call(O, "DOMReady", [], N); }, 0); } else { this.DOMReadyEvent.subscribe(L, N, M); } }, onContentReady: function (N, L, O, M) { F.push({ id: N, fn: L, obj: O, override: M, checkReady: true }); C = this.POLL_RETRYS; this.startInterval(); }, addListener: function (N, L, W, R, M) { if (!W || !W.call) { return false; } if (this._isValidCollection(N)) { var X = true; for (var S = 0, U = N.length; S < U; ++S) { X = this.on(N[S], L, W, R, M) && X; } return X; } else { if (YAHOO.lang.isString(N)) { var Q = this.getEl(N); if (Q) { N = Q; } else { this.onAvailable(N, function () { YAHOO.util.Event.on(N, L, W, R, M); }); return true; } } } if (!N) { return false; } if ("unload" == L && R !== this) { K[K.length] = [N, L, W, R, M]; return true; } var Z = N; if (M) { if (M === true) { Z = R; } else { Z = M; } } var O = function (a) { return W.call(Z, YAHOO.util.Event.getEvent(a, N), R); }; var Y = [N, L, W, O, Z, R, M]; var T = I.length; I[T] = Y; if (this.useLegacyEvent(N, L)) { var P = this.getLegacyIndex(N, L); if (P == -1 || N != G[P][0]) { P = G.length; B[N.id + L] = P; G[P] = [N, L, N["on" + L]]; E[P] = []; N["on" + L] = function (a) { YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(a), P); }; } E[P].push(Y); } else { try { this._simpleAdd(N, L, O, false); } catch (V) { this.lastError = V; this.removeListener(N, L, W); return false; } } return true; }, fireLegacyEvent: function (P, N) { var R = true, L, T, S, U, Q; T = E[N]; for (var M = 0, O = T.length; M < O; ++M) { S = T[M]; if (S && S[this.WFN]) { U = S[this.ADJ_SCOPE]; Q = S[this.WFN].call(U, P); R = (R && Q); } } L = G[N]; if (L && L[2]) { L[2](P); } return R; }, getLegacyIndex: function (M, N) { var L = this.generateId(M) + N; if (typeof B[L] == "undefined") { return -1; } else { return B[L]; } }, useLegacyEvent: function (M, N) { if (this.webkit && ("click" == N || "dblclick" == N)) { var L = parseInt(this.webkit, 10); if (!isNaN(L) && L < 418) { return true; } } return false; }, removeListener: function (M, L, U) { var P, S, W; if (typeof M == "string") { M = this.getEl(M); } else { if (this._isValidCollection(M)) { var V = true; for (P = 0, S = M.length; P < S; ++P) { V = (this.removeListener(M[P], L, U) && V); } return V; } } if (!U || !U.call) { return this.purgeElement(M, false, L); } if ("unload" == L) { for (P = 0, S = K.length; P < S; P++) { W = K[P]; if (W && W[0] == M && W[1] == L && W[2] == U) { K[P] = null; return true; } } return false; } var Q = null; var R = arguments[3]; if ("undefined" === typeof R) { R = this._getCacheIndex(M, L, U); } if (R >= 0) { Q = I[R]; } if (!M || !Q) { return false; } if (this.useLegacyEvent(M, L)) { var O = this.getLegacyIndex(M, L); var N = E[O]; if (N) { for (P = 0, S = N.length; P < S; ++P) { W = N[P]; if (W && W[this.EL] == M && W[this.TYPE] == L && W[this.FN] == U) { N[P] = null; break; } } } } else { try { this._simpleRemove(M, L, Q[this.WFN], false); } catch (T) { this.lastError = T; return false; } } delete I[R][this.WFN]; delete I[R][this.FN]; I[R] = null; return true; }, getTarget: function (N, M) { var L = N.target || N.srcElement; return this.resolveTextNode(L); }, resolveTextNode: function (L) { if (L && 3 == L.nodeType) { return L.parentNode; } else { return L; } }, getPageX: function (M) { var L = M.pageX; if (!L && 0 !== L) { L = M.clientX || 0; if (this.isIE) { L += this._getScrollLeft(); } } return L; }, getPageY: function (L) { var M = L.pageY; if (!M && 0 !== M) { M = L.clientY || 0; if (this.isIE) { M += this._getScrollTop(); } } return M; }, getXY: function (L) { return [this.getPageX(L), this.getPageY(L)]; }, getRelatedTarget: function (M) { var L = M.relatedTarget; if (!L) { if (M.type == "mouseout") { L = M.toElement; } else { if (M.type == "mouseover") { L = M.fromElement; } } } return this.resolveTextNode(L); }, getTime: function (N) { if (!N.time) { var M = new Date().getTime(); try { N.time = M; } catch (L) { this.lastError = L; return M; } } return N.time; }, stopEvent: function (L) { this.stopPropagation(L); this.preventDefault(L); }, stopPropagation: function (L) { if (L.stopPropagation) { L.stopPropagation(); } else { L.cancelBubble = true; } }, preventDefault: function (L) { if (L.preventDefault) { L.preventDefault(); } else { L.returnValue = false; } }, getEvent: function (Q, O) { var P = Q || window.event; if (!P) { var R = this.getEvent.caller; while (R) { P = R.arguments[0]; if (P && Event == P.constructor) { break; } R = R.caller; } } if (P && this.isIE) { try { var N = P.srcElement; if (N) { var M = N.type; } } catch (L) { P.target = O; } } return P; }, getCharCode: function (M) { var L = M.keyCode || M.charCode || 0; if (YAHOO.env.ua.webkit && (L in D)) { L = D[L]; } return L; }, _getCacheIndex: function (P, Q, O) { for (var N = 0, M = I.length; N < M; ++N) { var L = I[N]; if (L && L[this.FN] == O && L[this.EL] == P && L[this.TYPE] == Q) { return N; } } return -1; }, generateId: function (L) { var M = L.id; if (!M) { M = "yuievtautoid-" + A; ++A; L.id = M; } return M; }, _isValidCollection: function (M) { try { return (typeof M !== "string" && M.length && !M.tagName && !M.alert && typeof M[0] !== "undefined"); } catch (L) { return false; } }, elCache: {}, getEl: function (L) { return (typeof L === "string") ? document.getElementById(L) : L; }, clearCache: function () { }, DOMReadyEvent: new YAHOO.util.CustomEvent("DOMReady", this), _load: function (M) { if (!H) { H = true; var L = YAHOO.util.Event; L._ready(); L._tryPreloadAttach(); } }, _ready: function (M) { if (!J) { J = true; var L = YAHOO.util.Event; L.DOMReadyEvent.fire(); L._simpleRemove(document, "DOMContentLoaded", L._ready); } }, _tryPreloadAttach: function () { if (this.locked) { return false; } if (this.isIE) { if (!J) { this.startInterval(); return false; } } this.locked = true; var Q = !H; if (!Q) { Q = (C > 0); } var P = []; var R = function (T, U) { var S = T; if (U.override) { if (U.override === true) { S = U.obj; } else { S = U.override; } } U.fn.call(S, U.obj); }; var M, L, O, N; for (M = 0, L = F.length; M < L; ++M) { O = F[M]; if (O && !O.checkReady) { N = this.getEl(O.id); if (N) { R(N, O); F[M] = null; } else { P.push(O); } } } for (M = 0, L = F.length; M < L; ++M) { O = F[M]; if (O && O.checkReady) { N = this.getEl(O.id); if (N) { if (H || N.nextSibling) { R(N, O); F[M] = null; } } else { P.push(O); } } } C = (P.length === 0) ? 0 : C - 1; if (Q) { this.startInterval(); } else { clearInterval(this._interval); this._interval = null; } this.locked = false; return true; }, purgeElement: function (O, P, R) { var Q = this.getListeners(O, R), N, L; if (Q) { for (N = 0, L = Q.length; N < L; ++N) { var M = Q[N]; this.removeListener(O, M.type, M.fn, M.index); } } if (P && O && O.childNodes) { for (N = 0, L = O.childNodes.length; N < L; ++N) { this.purgeElement(O.childNodes[N], P, R); } } }, getListeners: function (N, L) { var Q = [], M; if (!L) { M = [I, K]; } else { if (L == "unload") { M = [K]; } else { M = [I]; } } for (var P = 0; P < M.length; P = P + 1) { var T = M[P]; if (T && T.length > 0) { for (var R = 0, S = T.length; R < S; ++R) { var O = T[R]; if (O && O[this.EL] === N && (!L || L === O[this.TYPE])) { Q.push({ type: O[this.TYPE], fn: O[this.FN], obj: O[this.OBJ], adjust: O[this.OVERRIDE], scope: O[this.ADJ_SCOPE], index: R }); } } } } return (Q.length) ? Q : null; }, _unload: function (S) { var R = YAHOO.util.Event, P, O, M, L, N; for (P = 0, L = K.length; P < L; ++P) { M = K[P]; if (M) { var Q = window; if (M[R.ADJ_SCOPE]) { if (M[R.ADJ_SCOPE] === true) { Q = M[R.UNLOAD_OBJ]; } else { Q = M[R.ADJ_SCOPE]; } } M[R.FN].call(Q, R.getEvent(S, M[R.EL]), M[R.UNLOAD_OBJ]); K[P] = null; M = null; Q = null; } } K = null; if (I && I.length > 0) { O = I.length; while (O) { N = O - 1; M = I[N]; if (M) { R.removeListener(M[R.EL], M[R.TYPE], M[R.FN], N); } O = O - 1; } M = null; R.clearCache(); } for (P = 0, L = G.length; P < L; ++P) { G[P][0] = null; G[P] = null; } G = null; R._simpleRemove(window, "unload", R._unload); }, _getScrollLeft: function () { return this._getScroll()[1]; }, _getScrollTop: function () { return this._getScroll()[0]; }, _getScroll: function () { var L = document.documentElement, M = document.body; if (L && (L.scrollTop || L.scrollLeft)) { return [L.scrollTop, L.scrollLeft]; } else { if (M) { return [M.scrollTop, M.scrollLeft]; } else { return [0, 0]; } } }, regCE: function () { }, _simpleAdd: function () { if (window.addEventListener) { return function (N, O, M, L) { N.addEventListener(O, M, (L)); }; } else { if (window.attachEvent) { return function (N, O, M, L) { N.attachEvent("on" + O, M); }; } else { return function () { }; } } } (), _simpleRemove: function () { if (window.removeEventListener) { return function (N, O, M, L) { N.removeEventListener(O, M, (L)); }; } else { if (window.detachEvent) { return function (M, N, L) { M.detachEvent("on" + N, L); }; } else { return function () { }; } } } () }; } (); (function () { var D = YAHOO.util.Event; D.on = D.addListener; if (D.isIE) { YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach, YAHOO.util.Event, true); var B, E = document, A = E.body; if (("undefined" !== typeof YAHOO_config) && YAHOO_config.injecting) { B = document.createElement("script"); var C = E.getElementsByTagName("head")[0] || A; C.insertBefore(B, C.firstChild); } else { E.write('<script id="_yui_eu_dr" defer="true" src="//:"><\/script>'); B = document.getElementById("_yui_eu_dr"); } if (B) { B.onreadystatechange = function () { if ("complete" === this.readyState) { this.parentNode.removeChild(this); YAHOO.util.Event._ready(); } }; } else { } B = null; } else { if (D.webkit) { D._drwatch = setInterval(function () { var F = document.readyState; if ("loaded" == F || "complete" == F) { clearInterval(D._drwatch); D._drwatch = null; D._ready(); } }, D.POLL_INTERVAL); } else { D._simpleAdd(document, "DOMContentLoaded", D._ready); } } D._simpleAdd(window, "load", D._load); D._simpleAdd(window, "unload", D._unload); D._tryPreloadAttach(); })(); } YAHOO.util.EventProvider = function () { }; YAHOO.util.EventProvider.prototype = { __yui_events: null, __yui_subscribers: null, subscribe: function (A, C, F, E) { this.__yui_events = this.__yui_events || {}; var D = this.__yui_events[A]; if (D) { D.subscribe(C, F, E); } else { this.__yui_subscribers = this.__yui_subscribers || {}; var B = this.__yui_subscribers; if (!B[A]) { B[A] = []; } B[A].push({ fn: C, obj: F, override: E }); } }, unsubscribe: function (C, E, G) { this.__yui_events = this.__yui_events || {}; var A = this.__yui_events; if (C) { var F = A[C]; if (F) { return F.unsubscribe(E, G); } } else { var B = true; for (var D in A) { if (YAHOO.lang.hasOwnProperty(A, D)) { B = B && A[D].unsubscribe(E, G); } } return B; } return false; }, unsubscribeAll: function (A) { return this.unsubscribe(A); }, createEvent: function (G, D) { this.__yui_events = this.__yui_events || {}; var A = D || {}; var I = this.__yui_events; if (I[G]) { } else { var H = A.scope || this; var E = (A.silent); var B = new YAHOO.util.CustomEvent(G, H, E, YAHOO.util.CustomEvent.FLAT); I[G] = B; if (A.onSubscribeCallback) { B.subscribeEvent.subscribe(A.onSubscribeCallback); } this.__yui_subscribers = this.__yui_subscribers || {}; var F = this.__yui_subscribers[G]; if (F) { for (var C = 0; C < F.length; ++C) { B.subscribe(F[C].fn, F[C].obj, F[C].override); } } } return I[G]; }, fireEvent: function (E, D, A, C) { this.__yui_events = this.__yui_events || {}; var G = this.__yui_events[E]; if (!G) { return null; } var B = []; for (var F = 1; F < arguments.length; ++F) { B.push(arguments[F]); } return G.fire.apply(G, B); }, hasEvent: function (A) { if (this.__yui_events) { if (this.__yui_events[A]) { return true; } } return false; } }; YAHOO.util.KeyListener = function (A, F, B, C) { if (!A) { } else { if (!F) { } else { if (!B) { } } } if (!C) { C = YAHOO.util.KeyListener.KEYDOWN; } var D = new YAHOO.util.CustomEvent("keyPressed"); this.enabledEvent = new YAHOO.util.CustomEvent("enabled"); this.disabledEvent = new YAHOO.util.CustomEvent("disabled"); if (typeof A == "string") { A = document.getElementById(A); } if (typeof B == "function") { D.subscribe(B); } else { D.subscribe(B.fn, B.scope, B.correctScope); } function E(K, J) { if (!F.shift) { F.shift = false; } if (!F.alt) { F.alt = false; } if (!F.ctrl) { F.ctrl = false; } if (K.shiftKey == F.shift && K.altKey == F.alt && K.ctrlKey == F.ctrl) { var H; var G; if (F.keys instanceof Array) { for (var I = 0; I < F.keys.length; I++) { H = F.keys[I]; if (H == K.charCode) { D.fire(K.charCode, K); break; } else { if (H == K.keyCode) { D.fire(K.keyCode, K); break; } } } } else { H = F.keys; if (H == K.charCode) { D.fire(K.charCode, K); } else { if (H == K.keyCode) { D.fire(K.keyCode, K); } } } } } this.enable = function () { if (!this.enabled) { YAHOO.util.Event.addListener(A, C, E); this.enabledEvent.fire(F); } this.enabled = true; }; this.disable = function () { if (this.enabled) { YAHOO.util.Event.removeListener(A, C, E); this.disabledEvent.fire(F); } this.enabled = false; }; this.toString = function () { return "KeyListener [" + F.keys + "] " + A.tagName + (A.id ? "[" + A.id + "]" : ""); }; }; YAHOO.util.KeyListener.KEYDOWN = "keydown"; YAHOO.util.KeyListener.KEYUP = "keyup"; YAHOO.register("event", YAHOO.util.Event, { version: "2.3.1", build: "541" }); YAHOO.register("yahoo-dom-event", YAHOO, { version: "2.3.1", build: "541" });
// YUI version 2.3.1: /build/animation/animation.js
YAHOO.util.Anim = function (el, attributes, duration, method) { if (!el) { } this.init(el, attributes, duration, method); }; YAHOO.util.Anim.prototype = { toString: function () { var el = this.getEl(); var id = el.id || el.tagName || el; return ("Anim " + id); }, patterns: { noNegatives: /width|height|opacity|padding/i, offsetAttribute: /^((width|height)|(top|left))$/, defaultUnit: /width|height|top$|bottom$|left$|right$/i, offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i }, doMethod: function (attr, start, end) { return this.method(this.currentFrame, start, end - start, this.totalFrames); }, setAttribute: function (attr, val, unit) { if (this.patterns.noNegatives.test(attr)) { val = (val > 0) ? val : 0; } YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); }, getAttribute: function (attr) { var el = this.getEl(); var val = YAHOO.util.Dom.getStyle(el, attr); if (val !== "auto" && !this.patterns.offsetUnit.test(val)) { return parseFloat(val); } var a = this.patterns.offsetAttribute.exec(attr) || []; var pos = !!(a[3]); var box = !!(a[2]); if (box || (YAHOO.util.Dom.getStyle(el, "position") == "absolute" && pos)) { val = el["offset" + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; } else { val = 0; } return val; }, getDefaultUnit: function (attr) { if (this.patterns.defaultUnit.test(attr)) { return "px"; } return ""; }, setRuntimeAttribute: function (attr) { var start; var end; var attributes = this.attributes; this.runtimeAttributes[attr] = {}; var isset = function (prop) { return (typeof prop !== "undefined"); }; if (!isset(attributes[attr]["to"]) && !isset(attributes[attr]["by"])) { return false; } start = (isset(attributes[attr]["from"])) ? attributes[attr]["from"] : this.getAttribute(attr); if (isset(attributes[attr]["to"])) { end = attributes[attr]["to"]; } else { if (isset(attributes[attr]["by"])) { if (start.constructor == Array) { end = []; for (var i = 0, len = start.length; i < len; ++i) { end[i] = start[i] + attributes[attr]["by"][i] * 1; } } else { end = start + attributes[attr]["by"] * 1; } } } this.runtimeAttributes[attr].start = start; this.runtimeAttributes[attr].end = end; this.runtimeAttributes[attr].unit = (isset(attributes[attr].unit)) ? attributes[attr]["unit"] : this.getDefaultUnit(attr); return true; }, init: function (el, attributes, duration, method) { var isAnimated = false; var startTime = null; var actualFrames = 0; el = YAHOO.util.Dom.get(el); this.attributes = attributes || {}; this.duration = !YAHOO.lang.isUndefined(duration) ? duration : 1; this.method = method || YAHOO.util.Easing.easeNone; this.useSeconds = true; this.currentFrame = 0; this.totalFrames = YAHOO.util.AnimMgr.fps; this.setEl = function (element) { el = YAHOO.util.Dom.get(element); }; this.getEl = function () { return el; }; this.isAnimated = function () { return isAnimated; }; this.getStartTime = function () { return startTime; }; this.runtimeAttributes = {}; this.animate = function () { if (this.isAnimated()) { return false; } this.currentFrame = 0; this.totalFrames = (this.useSeconds) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; if (this.duration === 0 && this.useSeconds) { this.totalFrames = 1; } YAHOO.util.AnimMgr.registerElement(this); return true; }; this.stop = function (finish) { if (finish) { this.currentFrame = this.totalFrames; this._onTween.fire(); } YAHOO.util.AnimMgr.stop(this); }; var onStart = function () { this.onStart.fire(); this.runtimeAttributes = {}; for (var attr in this.attributes) { this.setRuntimeAttribute(attr); } isAnimated = true; actualFrames = 0; startTime = new Date(); }; var onTween = function () { var data = { duration: new Date() - this.getStartTime(), currentFrame: this.currentFrame }; data.toString = function () { return ("duration: " + data.duration + ", currentFrame: " + data.currentFrame); }; this.onTween.fire(data); var runtimeAttributes = this.runtimeAttributes; for (var attr in runtimeAttributes) { this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); } actualFrames += 1; }; var onComplete = function () { var actual_duration = (new Date() - startTime) / 1000; var data = { duration: actual_duration, frames: actualFrames, fps: actualFrames / actual_duration }; data.toString = function () { return ("duration: " + data.duration + ", frames: " + data.frames + ", fps: " + data.fps); }; isAnimated = false; actualFrames = 0; this.onComplete.fire(data); }; this._onStart = new YAHOO.util.CustomEvent("_start", this, true); this.onStart = new YAHOO.util.CustomEvent("start", this); this.onTween = new YAHOO.util.CustomEvent("tween", this); this._onTween = new YAHOO.util.CustomEvent("_tween", this, true); this.onComplete = new YAHOO.util.CustomEvent("complete", this); this._onComplete = new YAHOO.util.CustomEvent("_complete", this, true); this._onStart.subscribe(onStart); this._onTween.subscribe(onTween); this._onComplete.subscribe(onComplete); } }; YAHOO.util.AnimMgr = new function () { var thread = null; var queue = []; var tweenCount = 0; this.fps = 1000; this.delay = 1; this.registerElement = function (tween) { queue[queue.length] = tween; tweenCount += 1; tween._onStart.fire(); this.start(); }; this.unRegister = function (tween, index) { tween._onComplete.fire(); index = index || getIndex(tween); if (index == -1) { return false; } queue.splice(index, 1); tweenCount -= 1; if (tweenCount <= 0) { this.stop(); } return true; }; this.start = function () { if (thread === null) { thread = setInterval(this.run, this.delay); } }; this.stop = function (tween) { if (!tween) { clearInterval(thread); for (var i = 0, len = queue.length; i < len; ++i) { if (queue[0].isAnimated()) { this.unRegister(queue[0], 0); } } queue = []; thread = null; tweenCount = 0; } else { this.unRegister(tween); } }; this.run = function () { for (var i = 0, len = queue.length; i < len; ++i) { var tween = queue[i]; if (!tween || !tween.isAnimated()) { continue; } if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) { tween.currentFrame += 1; if (tween.useSeconds) { correctFrame(tween); } tween._onTween.fire(); } else { YAHOO.util.AnimMgr.stop(tween, i); } } }; var getIndex = function (anim) { for (var i = 0, len = queue.length; i < len; ++i) { if (queue[i] == anim) { return i; } } return -1; }; var correctFrame = function (tween) { var frames = tween.totalFrames; var frame = tween.currentFrame; var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); var elapsed = (new Date() - tween.getStartTime()); var tweak = 0; if (elapsed < tween.duration * 1000) { tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); } else { tweak = frames - (frame + 1); } if (tweak > 0 && isFinite(tweak)) { if (tween.currentFrame + tweak >= frames) { tweak = frames - (frame + 1); } tween.currentFrame += tweak; } }; }; YAHOO.util.Bezier = new function () { this.getPosition = function (points, t) { var n = points.length; var tmp = []; for (var i = 0; i < n; ++i) { tmp[i] = [points[i][0], points[i][1]]; } for (var j = 1; j < n; ++j) { for (i = 0; i < n - j; ++i) { tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; } } return [tmp[0][0], tmp[0][1]]; }; }; (function () { YAHOO.util.ColorAnim = function (el, attributes, duration, method) { YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); }; YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); var Y = YAHOO.util; var superclass = Y.ColorAnim.superclass; var proto = Y.ColorAnim.prototype; proto.toString = function () { var el = this.getEl(); var id = el.id || el.tagName; return ("ColorAnim " + id); }; proto.patterns.color = /color$/i; proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; proto.parseColor = function (s) { if (s.length == 3) { return s; } var c = this.patterns.hex.exec(s); if (c && c.length == 4) { return [parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16)]; } c = this.patterns.rgb.exec(s); if (c && c.length == 4) { return [parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10)]; } c = this.patterns.hex3.exec(s); if (c && c.length == 4) { return [parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16)]; } return null; }; proto.getAttribute = function (attr) { var el = this.getEl(); if (this.patterns.color.test(attr)) { var val = YAHOO.util.Dom.getStyle(el, attr); if (this.patterns.transparent.test(val)) { var parent = el.parentNode; val = Y.Dom.getStyle(parent, attr); while (parent && this.patterns.transparent.test(val)) { parent = parent.parentNode; val = Y.Dom.getStyle(parent, attr); if (parent.tagName.toUpperCase() == "HTML") { val = "#fff"; } } } } else { val = superclass.getAttribute.call(this, attr); } return val; }; proto.doMethod = function (attr, start, end) { var val; if (this.patterns.color.test(attr)) { val = []; for (var i = 0, len = start.length; i < len; ++i) { val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); } val = "rgb(" + Math.floor(val[0]) + "," + Math.floor(val[1]) + "," + Math.floor(val[2]) + ")"; } else { val = superclass.doMethod.call(this, attr, start, end); } return val; }; proto.setRuntimeAttribute = function (attr) { superclass.setRuntimeAttribute.call(this, attr); if (this.patterns.color.test(attr)) { var attributes = this.attributes; var start = this.parseColor(this.runtimeAttributes[attr].start); var end = this.parseColor(this.runtimeAttributes[attr].end); if (typeof attributes[attr]["to"] === "undefined" && typeof attributes[attr]["by"] !== "undefined") { end = this.parseColor(attributes[attr].by); for (var i = 0, len = start.length; i < len; ++i) { end[i] = start[i] + end[i]; } } this.runtimeAttributes[attr].start = start; this.runtimeAttributes[attr].end = end; } }; })(); YAHOO.util.Easing = { easeNone: function (t, b, c, d) { return c * t / d + b; }, easeIn: function (t, b, c, d) { return c * (t /= d) * t + b; }, easeOut: function (t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, easeBoth: function (t, b, c, d) { if ((t /= d / 2) < 1) { return c / 2 * t * t + b; } return -c / 2 * ((--t) * (t - 2) - 1) + b; }, easeInStrong: function (t, b, c, d) { return c * (t /= d) * t * t * t + b; }, easeOutStrong: function (t, b, c, d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; }, easeBothStrong: function (t, b, c, d) { if ((t /= d / 2) < 1) { return c / 2 * t * t * t * t + b; } return -c / 2 * ((t -= 2) * t * t * t - 2) + b; }, elasticIn: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ((t /= d) == 1) { return b + c; } if (!p) { p = d * 0.3; } if (!a || a < Math.abs(c)) { a = c; var s = p / 4; } else { var s = p / (2 * Math.PI) * Math.asin(c / a); } return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; }, elasticOut: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ((t /= d) == 1) { return b + c; } if (!p) { p = d * 0.3; } if (!a || a < Math.abs(c)) { a = c; var s = p / 4; } else { var s = p / (2 * Math.PI) * Math.asin(c / a); } return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b; }, elasticBoth: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ((t /= d / 2) == 2) { return b + c; } if (!p) { p = d * (0.3 * 1.5); } if (!a || a < Math.abs(c)) { a = c; var s = p / 4; } else { var s = p / (2 * Math.PI) * Math.asin(c / a); } if (t < 1) { return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; } return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * 0.5 + c + b; }, backIn: function (t, b, c, d, s) { if (typeof s == "undefined") { s = 1.70158; } return c * (t /= d) * t * ((s + 1) * t - s) + b; }, backOut: function (t, b, c, d, s) { if (typeof s == "undefined") { s = 1.70158; } return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, backBoth: function (t, b, c, d, s) { if (typeof s == "undefined") { s = 1.70158; } if ((t /= d / 2) < 1) { return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; } return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; }, bounceIn: function (t, b, c, d) { return c - YAHOO.util.Easing.bounceOut(d - t, 0, c, d) + b; }, bounceOut: function (t, b, c, d) { if ((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else { if (t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b; } else { if (t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b; } } } return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b; }, bounceBoth: function (t, b, c, d) { if (t < d / 2) { return YAHOO.util.Easing.bounceIn(t * 2, 0, c, d) * 0.5 + b; } return YAHOO.util.Easing.bounceOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b; } }; (function () { YAHOO.util.Motion = function (el, attributes, duration, method) { if (el) { YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); } }; YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); var Y = YAHOO.util; var superclass = Y.Motion.superclass; var proto = Y.Motion.prototype; proto.toString = function () { var el = this.getEl(); var id = el.id || el.tagName; return ("Motion " + id); }; proto.patterns.points = /^points$/i; proto.setAttribute = function (attr, val, unit) { if (this.patterns.points.test(attr)) { unit = unit || "px"; superclass.setAttribute.call(this, "left", val[0], unit); superclass.setAttribute.call(this, "top", val[1], unit); } else { superclass.setAttribute.call(this, attr, val, unit); } }; proto.getAttribute = function (attr) { if (this.patterns.points.test(attr)) { var val = [superclass.getAttribute.call(this, "left"), superclass.getAttribute.call(this, "top")]; } else { val = superclass.getAttribute.call(this, attr); } return val; }; proto.doMethod = function (attr, start, end) { var val = null; if (this.patterns.points.test(attr)) { var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); } else { val = superclass.doMethod.call(this, attr, start, end); } return val; }; proto.setRuntimeAttribute = function (attr) { if (this.patterns.points.test(attr)) { var el = this.getEl(); var attributes = this.attributes; var start; var control = attributes["points"]["control"] || []; var end; var i, len; if (control.length > 0 && !(control[0] instanceof Array)) { control = [control]; } else { var tmp = []; for (i = 0, len = control.length; i < len; ++i) { tmp[i] = control[i]; } control = tmp; } if (Y.Dom.getStyle(el, "position") == "static") { Y.Dom.setStyle(el, "position", "relative"); } if (isset(attributes["points"]["from"])) { Y.Dom.setXY(el, attributes["points"]["from"]); } else { Y.Dom.setXY(el, Y.Dom.getXY(el)); } start = this.getAttribute("points"); if (isset(attributes["points"]["to"])) { end = translateValues.call(this, attributes["points"]["to"], start); var pageXY = Y.Dom.getXY(this.getEl()); for (i = 0, len = control.length; i < len; ++i) { control[i] = translateValues.call(this, control[i], start); } } else { if (isset(attributes["points"]["by"])) { end = [start[0] + attributes["points"]["by"][0], start[1] + attributes["points"]["by"][1]]; for (i = 0, len = control.length; i < len; ++i) { control[i] = [start[0] + control[i][0], start[1] + control[i][1]]; } } } this.runtimeAttributes[attr] = [start]; if (control.length > 0) { this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); } this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; } else { superclass.setRuntimeAttribute.call(this, attr); } }; var translateValues = function (val, start) { var pageXY = Y.Dom.getXY(this.getEl()); val = [val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1]]; return val; }; var isset = function (prop) { return (typeof prop !== "undefined"); }; })(); (function () { YAHOO.util.Scroll = function (el, attributes, duration, method) { if (el) { YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); } }; YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); var Y = YAHOO.util; var superclass = Y.Scroll.superclass; var proto = Y.Scroll.prototype; proto.toString = function () { var el = this.getEl(); var id = el.id || el.tagName; return ("Scroll " + id); }; proto.doMethod = function (attr, start, end) { var val = null; if (attr == "scroll") { val = [this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)]; } else { val = superclass.doMethod.call(this, attr, start, end); } return val; }; proto.getAttribute = function (attr) { var val = null; var el = this.getEl(); if (attr == "scroll") { val = [el.scrollLeft, el.scrollTop]; } else { val = superclass.getAttribute.call(this, attr); } return val; }; proto.setAttribute = function (attr, val, unit) { var el = this.getEl(); if (attr == "scroll") { el.scrollLeft = val[0]; el.scrollTop = val[1]; } else { superclass.setAttribute.call(this, attr, val, unit); } }; })(); YAHOO.register("animation", YAHOO.util.Anim, { version: "2.3.1", build: "541" });
// YUI version 2.3.1: /build/container/container.js
(function () { YAHOO.util.Config = function (owner) { if (owner) { this.init(owner); } if (!owner) { } }; var Lang = YAHOO.lang, CustomEvent = YAHOO.util.CustomEvent, Config = YAHOO.util.Config; Config.CONFIG_CHANGED_EVENT = "configChanged"; Config.BOOLEAN_TYPE = "boolean"; Config.prototype = { owner: null, queueInProgress: false, config: null, initialConfig: null, eventQueue: null, configChangedEvent: null, init: function (owner) { this.owner = owner; this.configChangedEvent = this.createEvent(Config.CONFIG_CHANGED_EVENT); this.configChangedEvent.signature = CustomEvent.LIST; this.queueInProgress = false; this.config = {}; this.initialConfig = {}; this.eventQueue = []; }, checkBoolean: function (val) { return (typeof val == Config.BOOLEAN_TYPE); }, checkNumber: function (val) { return (!isNaN(val)); }, fireEvent: function (key, value) { var property = this.config[key]; if (property && property.event) { property.event.fire(value); } }, addProperty: function (key, propertyObject) { key = key.toLowerCase(); this.config[key] = propertyObject; propertyObject.event = this.createEvent(key, { scope: this.owner }); propertyObject.event.signature = CustomEvent.LIST; propertyObject.key = key; if (propertyObject.handler) { propertyObject.event.subscribe(propertyObject.handler, this.owner); } this.setProperty(key, propertyObject.value, true); if (!propertyObject.suppressEvent) { this.queueProperty(key, propertyObject.value); } }, getConfig: function () { var cfg = {}, prop, property; for (prop in this.config) { property = this.config[prop]; if (property && property.event) { cfg[prop] = property.value; } } return cfg; }, getProperty: function (key) { var property = this.config[key.toLowerCase()]; if (property && property.event) { return property.value; } else { return undefined; } }, resetProperty: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event) { if (this.initialConfig[key] && !Lang.isUndefined(this.initialConfig[key])) { this.setProperty(key, this.initialConfig[key]); return true; } } else { return false; } }, setProperty: function (key, value, silent) { var property; key = key.toLowerCase(); if (this.queueInProgress && !silent) { this.queueProperty(key, value); return true; } else { property = this.config[key]; if (property && property.event) { if (property.validator && !property.validator(value)) { return false; } else { property.value = value; if (!silent) { this.fireEvent(key, value); this.configChangedEvent.fire([key, value]); } return true; } } else { return false; } } }, queueProperty: function (key, value) { key = key.toLowerCase(); var property = this.config[key], foundDuplicate = false, iLen, queueItem, queueItemKey, queueItemValue, sLen, supercedesCheck, qLen, queueItemCheck, queueItemCheckKey, queueItemCheckValue, i, s, q; if (property && property.event) { if (!Lang.isUndefined(value) && property.validator && !property.validator(value)) { return false; } else { if (!Lang.isUndefined(value)) { property.value = value; } else { value = property.value; } foundDuplicate = false; iLen = this.eventQueue.length; for (i = 0; i < iLen; i++) { queueItem = this.eventQueue[i]; if (queueItem) { queueItemKey = queueItem[0]; queueItemValue = queueItem[1]; if (queueItemKey == key) { this.eventQueue[i] = null; this.eventQueue.push([key, (!Lang.isUndefined(value) ? value : queueItemValue)]); foundDuplicate = true; break; } } } if (!foundDuplicate && !Lang.isUndefined(value)) { this.eventQueue.push([key, value]); } } if (property.supercedes) { sLen = property.supercedes.length; for (s = 0; s < sLen; s++) { supercedesCheck = property.supercedes[s]; qLen = this.eventQueue.length; for (q = 0; q < qLen; q++) { queueItemCheck = this.eventQueue[q]; if (queueItemCheck) { queueItemCheckKey = queueItemCheck[0]; queueItemCheckValue = queueItemCheck[1]; if (queueItemCheckKey == supercedesCheck.toLowerCase()) { this.eventQueue.push([queueItemCheckKey, queueItemCheckValue]); this.eventQueue[q] = null; break; } } } } } return true; } else { return false; } }, refireEvent: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event && !Lang.isUndefined(property.value)) { if (this.queueInProgress) { this.queueProperty(key); } else { this.fireEvent(key, property.value); } } }, applyConfig: function (userConfig, init) { var sKey, oValue, oConfig; if (init) { oConfig = {}; for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { oConfig[sKey.toLowerCase()] = userConfig[sKey]; } } this.initialConfig = oConfig; } for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { this.queueProperty(sKey, userConfig[sKey]); } } }, refresh: function () { var prop; for (prop in this.config) { this.refireEvent(prop); } }, fireQueue: function () { var i, queueItem, key, value, property; this.queueInProgress = true; for (i = 0; i < this.eventQueue.length; i++) { queueItem = this.eventQueue[i]; if (queueItem) { key = queueItem[0]; value = queueItem[1]; property = this.config[key]; property.value = value; this.fireEvent(key, value); } } this.queueInProgress = false; this.eventQueue = []; }, subscribeToConfigEvent: function (key, handler, obj, override) { var property = this.config[key.toLowerCase()]; if (property && property.event) { if (!Config.alreadySubscribed(property.event, handler, obj)) { property.event.subscribe(handler, obj, override); } return true; } else { return false; } }, unsubscribeFromConfigEvent: function (key, handler, obj) { var property = this.config[key.toLowerCase()]; if (property && property.event) { return property.event.unsubscribe(handler, obj); } else { return false; } }, toString: function () { var output = "Config"; if (this.owner) { output += " [" + this.owner.toString() + "]"; } return output; }, outputEventQueue: function () { var output = "", queueItem, q, nQueue = this.eventQueue.length; for (q = 0; q < nQueue; q++) { queueItem = this.eventQueue[q]; if (queueItem) { output += queueItem[0] + "=" + queueItem[1] + ", "; } } return output; }, destroy: function () { var oConfig = this.config, sProperty, oProperty; for (sProperty in oConfig) { if (Lang.hasOwnProperty(oConfig, sProperty)) { oProperty = oConfig[sProperty]; oProperty.event.unsubscribeAll(); oProperty.event = null; } } this.configChangedEvent.unsubscribeAll(); this.configChangedEvent = null; this.owner = null; this.config = null; this.initialConfig = null; this.eventQueue = null; } }; Config.alreadySubscribed = function (evt, fn, obj) { var nSubscribers = evt.subscribers.length, subsc, i; if (nSubscribers > 0) { i = nSubscribers - 1; do { subsc = evt.subscribers[i]; if (subsc && subsc.obj == obj && subsc.fn == fn) { return true; } } while (i--); } return false; }; YAHOO.lang.augmentProto(Config, YAHOO.util.EventProvider); } ()); (function () { YAHOO.widget.Module = function (el, userConfig) { if (el) { this.init(el, userConfig); } else { } }; var Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, Event = YAHOO.util.Event, CustomEvent = YAHOO.util.CustomEvent, Module = YAHOO.widget.Module, m_oModuleTemplate, m_oHeaderTemplate, m_oBodyTemplate, m_oFooterTemplate, EVENT_TYPES = { "BEFORE_INIT": "beforeInit", "INIT": "init", "APPEND": "append", "BEFORE_RENDER": "beforeRender", "RENDER": "render", "CHANGE_HEADER": "changeHeader", "CHANGE_BODY": "changeBody", "CHANGE_FOOTER": "changeFooter", "CHANGE_CONTENT": "changeContent", "DESTORY": "destroy", "BEFORE_SHOW": "beforeShow", "SHOW": "show", "BEFORE_HIDE": "beforeHide", "HIDE": "hide" }, DEFAULT_CONFIG = { "VISIBLE": { key: "visible", value: true, validator: YAHOO.lang.isBoolean }, "EFFECT": { key: "effect", suppressEvent: true, supercedes: ["visible"] }, "MONITOR_RESIZE": { key: "monitorresize", value: true }, "APPEND_TO_DOCUMENT_BODY": { key: "appendtodocumentbody", value: false} }; Module.IMG_ROOT = null; Module.IMG_ROOT_SSL = null; Module.CSS_MODULE = "yui-module"; Module.CSS_HEADER = "hd"; Module.CSS_BODY = "bd"; Module.CSS_FOOTER = "ft"; Module.RESIZE_MONITOR_SECURE_URL = "javascript:false;"; Module.textResizeEvent = new CustomEvent("textResize"); function createModuleTemplate() { if (!m_oModuleTemplate) { m_oModuleTemplate = document.createElement("div"); m_oModuleTemplate.innerHTML = ('<div class="' + Module.CSS_HEADER + '"></div>' + '<div class="' + Module.CSS_BODY + '"></div><div class="' + Module.CSS_FOOTER + '"></div>'); m_oHeaderTemplate = m_oModuleTemplate.firstChild; m_oBodyTemplate = m_oHeaderTemplate.nextSibling; m_oFooterTemplate = m_oBodyTemplate.nextSibling; } return m_oModuleTemplate; } function createHeader() { if (!m_oHeaderTemplate) { createModuleTemplate(); } return (m_oHeaderTemplate.cloneNode(false)); } function createBody() { if (!m_oBodyTemplate) { createModuleTemplate(); } return (m_oBodyTemplate.cloneNode(false)); } function createFooter() { if (!m_oFooterTemplate) { createModuleTemplate(); } return (m_oFooterTemplate.cloneNode(false)); } Module.prototype = { constructor: Module, element: null, header: null, body: null, footer: null, id: null, imageRoot: Module.IMG_ROOT, initEvents: function () { var SIGNATURE = CustomEvent.LIST; this.beforeInitEvent = this.createEvent(EVENT_TYPES.BEFORE_INIT); this.beforeInitEvent.signature = SIGNATURE; this.initEvent = this.createEvent(EVENT_TYPES.INIT); this.initEvent.signature = SIGNATURE; this.appendEvent = this.createEvent(EVENT_TYPES.APPEND); this.appendEvent.signature = SIGNATURE; this.beforeRenderEvent = this.createEvent(EVENT_TYPES.BEFORE_RENDER); this.beforeRenderEvent.signature = SIGNATURE; this.renderEvent = this.createEvent(EVENT_TYPES.RENDER); this.renderEvent.signature = SIGNATURE; this.changeHeaderEvent = this.createEvent(EVENT_TYPES.CHANGE_HEADER); this.changeHeaderEvent.signature = SIGNATURE; this.changeBodyEvent = this.createEvent(EVENT_TYPES.CHANGE_BODY); this.changeBodyEvent.signature = SIGNATURE; this.changeFooterEvent = this.createEvent(EVENT_TYPES.CHANGE_FOOTER); this.changeFooterEvent.signature = SIGNATURE; this.changeContentEvent = this.createEvent(EVENT_TYPES.CHANGE_CONTENT); this.changeContentEvent.signature = SIGNATURE; this.destroyEvent = this.createEvent(EVENT_TYPES.DESTORY); this.destroyEvent.signature = SIGNATURE; this.beforeShowEvent = this.createEvent(EVENT_TYPES.BEFORE_SHOW); this.beforeShowEvent.signature = SIGNATURE; this.showEvent = this.createEvent(EVENT_TYPES.SHOW); this.showEvent.signature = SIGNATURE; this.beforeHideEvent = this.createEvent(EVENT_TYPES.BEFORE_HIDE); this.beforeHideEvent.signature = SIGNATURE; this.hideEvent = this.createEvent(EVENT_TYPES.HIDE); this.hideEvent.signature = SIGNATURE; }, platform: function () { var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) { return "windows"; } else { if (ua.indexOf("macintosh") != -1) { return "mac"; } else { return false; } } } (), browser: function () { var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf("opera") != -1) { return "opera"; } else { if (ua.indexOf("msie 7") != -1) { return "ie7"; } else { if (ua.indexOf("msie") != -1) { return "ie"; } else { if (ua.indexOf("safari") != -1) { return "safari"; } else { if (ua.indexOf("gecko") != -1) { return "gecko"; } else { return false; } } } } } } (), isSecure: function () { if (window.location.href.toLowerCase().indexOf("https") === 0) { return true; } else { return false; } } (), initDefaultConfig: function () { this.cfg.addProperty(DEFAULT_CONFIG.VISIBLE.key, { handler: this.configVisible, value: DEFAULT_CONFIG.VISIBLE.value, validator: DEFAULT_CONFIG.VISIBLE.validator }); this.cfg.addProperty(DEFAULT_CONFIG.EFFECT.key, { suppressEvent: DEFAULT_CONFIG.EFFECT.suppressEvent, supercedes: DEFAULT_CONFIG.EFFECT.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.MONITOR_RESIZE.key, { handler: this.configMonitorResize, value: DEFAULT_CONFIG.MONITOR_RESIZE.value }); this.cfg.addProperty(DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.key, { value: DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.value }); }, init: function (el, userConfig) { var elId, i, child; this.initEvents(); this.beforeInitEvent.fire(Module); this.cfg = new Config(this); if (this.isSecure) { this.imageRoot = Module.IMG_ROOT_SSL; } if (typeof el == "string") { elId = el; el = document.getElementById(el); if (!el) { el = (createModuleTemplate()).cloneNode(false); el.id = elId; } } this.element = el; if (el.id) { this.id = el.id; } child = this.element.firstChild; if (child) { var fndHd = false, fndBd = false, fndFt = false; do { if (1 == child.nodeType) { if (!fndHd && Dom.hasClass(child, Module.CSS_HEADER)) { this.header = child; fndHd = true; } else { if (!fndBd && Dom.hasClass(child, Module.CSS_BODY)) { this.body = child; fndBd = true; } else { if (!fndFt && Dom.hasClass(child, Module.CSS_FOOTER)) { this.footer = child; fndFt = true; } } } } } while ((child = child.nextSibling)); } this.initDefaultConfig(); Dom.addClass(this.element, Module.CSS_MODULE); if (userConfig) { this.cfg.applyConfig(userConfig, true); } if (!Config.alreadySubscribed(this.renderEvent, this.cfg.fireQueue, this.cfg)) { this.renderEvent.subscribe(this.cfg.fireQueue, this.cfg, true); } this.initEvent.fire(Module); }, initResizeMonitor: function () { var oDoc, oIFrame, sHTML; function fireTextResize() { Module.textResizeEvent.fire(); } if (!YAHOO.env.ua.opera) { oIFrame = Dom.get("_yuiResizeMonitor"); if (!oIFrame) { oIFrame = document.createElement("iframe"); if (this.isSecure && Module.RESIZE_MONITOR_SECURE_URL && YAHOO.env.ua.ie) { oIFrame.src = Module.RESIZE_MONITOR_SECURE_URL; } if (YAHOO.env.ua.gecko) { sHTML = "<html><head><script " + 'type="text/javascript">' + "window.onresize=function(){window.parent." + "YAHOO.widget.Module.textResizeEvent." + "fire();};window.parent.YAHOO.widget.Module." + "textResizeEvent.fire();<\/script></head>" + "<body></body></html>"; oIFrame.src = "data:text/html;charset=utf-8," + encodeURIComponent(sHTML); } oIFrame.id = "_yuiResizeMonitor"; oIFrame.style.position = "absolute"; oIFrame.style.visibility = "hidden"; var fc = document.body.firstChild; if (fc) { document.body.insertBefore(oIFrame, fc); } else { document.body.appendChild(oIFrame); } oIFrame.style.width = "10em"; oIFrame.style.height = "10em"; oIFrame.style.top = (-1 * oIFrame.offsetHeight) + "px"; oIFrame.style.left = (-1 * oIFrame.offsetWidth) + "px"; oIFrame.style.borderWidth = "0"; oIFrame.style.visibility = "visible"; if (YAHOO.env.ua.webkit) { oDoc = oIFrame.contentWindow.document; oDoc.open(); oDoc.close(); } } if (oIFrame && oIFrame.contentWindow) { Module.textResizeEvent.subscribe(this.onDomResize, this, true); if (!Module.textResizeInitialized) { if (!Event.on(oIFrame.contentWindow, "resize", fireTextResize)) { Event.on(oIFrame, "resize", fireTextResize); } Module.textResizeInitialized = true; } this.resizeMonitor = oIFrame; } } }, onDomResize: function (e, obj) { var nLeft = -1 * this.resizeMonitor.offsetWidth, nTop = -1 * this.resizeMonitor.offsetHeight; this.resizeMonitor.style.top = nTop + "px"; this.resizeMonitor.style.left = nLeft + "px"; }, setHeader: function (headerContent) { var oHeader = this.header || (this.header = createHeader()); if (typeof headerContent == "string") { oHeader.innerHTML = headerContent; } else { oHeader.innerHTML = ""; oHeader.appendChild(headerContent); } this.changeHeaderEvent.fire(headerContent); this.changeContentEvent.fire(); }, appendToHeader: function (element) { var oHeader = this.header || (this.header = createHeader()); oHeader.appendChild(element); this.changeHeaderEvent.fire(element); this.changeContentEvent.fire(); }, setBody: function (bodyContent) { var oBody = this.body || (this.body = createBody()); if (typeof bodyContent == "string") { oBody.innerHTML = bodyContent; } else { oBody.innerHTML = ""; oBody.appendChild(bodyContent); } this.changeBodyEvent.fire(bodyContent); this.changeContentEvent.fire(); }, appendToBody: function (element) { var oBody = this.body || (this.body = createBody()); oBody.appendChild(element); this.changeBodyEvent.fire(element); this.changeContentEvent.fire(); }, setFooter: function (footerContent) { var oFooter = this.footer || (this.footer = createFooter()); if (typeof footerContent == "string") { oFooter.innerHTML = footerContent; } else { oFooter.innerHTML = ""; oFooter.appendChild(footerContent); } this.changeFooterEvent.fire(footerContent); this.changeContentEvent.fire(); }, appendToFooter: function (element) { var oFooter = this.footer || (this.footer = createFooter()); oFooter.appendChild(element); this.changeFooterEvent.fire(element); this.changeContentEvent.fire(); }, render: function (appendToNode, moduleElement) { var me = this, firstChild; function appendTo(parentNode) { if (typeof parentNode == "string") { parentNode = document.getElementById(parentNode); } if (parentNode) { me._addToParent(parentNode, me.element); me.appendEvent.fire(); } } this.beforeRenderEvent.fire(); if (!moduleElement) { moduleElement = this.element; } if (appendToNode) { appendTo(appendToNode); } else { if (!Dom.inDocument(this.element)) { return false; } } if (this.header && !Dom.inDocument(this.header)) { firstChild = moduleElement.firstChild; if (firstChild) { moduleElement.insertBefore(this.header, firstChild); } else { moduleElement.appendChild(this.header); } } if (this.body && !Dom.inDocument(this.body)) { if (this.footer && Dom.isAncestor(this.moduleElement, this.footer)) { moduleElement.insertBefore(this.body, this.footer); } else { moduleElement.appendChild(this.body); } } if (this.footer && !Dom.inDocument(this.footer)) { moduleElement.appendChild(this.footer); } this.renderEvent.fire(); return true; }, destroy: function () { var parent, e; if (this.element) { Event.purgeElement(this.element, true); parent = this.element.parentNode; } if (parent) { parent.removeChild(this.element); } this.element = null; this.header = null; this.body = null; this.footer = null; Module.textResizeEvent.unsubscribe(this.onDomResize, this); this.cfg.destroy(); this.cfg = null; this.destroyEvent.fire(); for (e in this) { if (e instanceof CustomEvent) { e.unsubscribeAll(); } } }, show: function () { this.cfg.setProperty("visible", true); }, hide: function () { this.cfg.setProperty("visible", false); }, configVisible: function (type, args, obj) { var visible = args[0]; if (visible) { this.beforeShowEvent.fire(); Dom.setStyle(this.element, "display", "block"); this.showEvent.fire(); } else { this.beforeHideEvent.fire(); Dom.setStyle(this.element, "display", "none"); this.hideEvent.fire(); } }, configMonitorResize: function (type, args, obj) { var monitor = args[0]; if (monitor) { this.initResizeMonitor(); } else { Module.textResizeEvent.unsubscribe(this.onDomResize, this, true); this.resizeMonitor = null; } }, _addToParent: function (parentNode, element) { if (!this.cfg.getProperty("appendtodocumentbody") && parentNode === document.body && parentNode.firstChild) { parentNode.insertBefore(element, parentNode.firstChild); } else { parentNode.appendChild(element); } }, toString: function () { return "Module " + this.id; } }; YAHOO.lang.augmentProto(Module, YAHOO.util.EventProvider); } ()); (function () { YAHOO.widget.Overlay = function (el, userConfig) { YAHOO.widget.Overlay.superclass.constructor.call(this, el, userConfig); }; var Lang = YAHOO.lang, CustomEvent = YAHOO.util.CustomEvent, Module = YAHOO.widget.Module, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, Overlay = YAHOO.widget.Overlay, m_oIFrameTemplate, EVENT_TYPES = { "BEFORE_MOVE": "beforeMove", "MOVE": "move" }, DEFAULT_CONFIG = { "X": { key: "x", validator: Lang.isNumber, suppressEvent: true, supercedes: ["iframe"] }, "Y": { key: "y", validator: Lang.isNumber, suppressEvent: true, supercedes: ["iframe"] }, "XY": { key: "xy", suppressEvent: true, supercedes: ["iframe"] }, "CONTEXT": { key: "context", suppressEvent: true, supercedes: ["iframe"] }, "FIXED_CENTER": { key: "fixedcenter", value: false, validator: Lang.isBoolean, supercedes: ["iframe", "visible"] }, "WIDTH": { key: "width", suppressEvent: true, supercedes: ["context", "fixedcenter", "iframe"] }, "HEIGHT": { key: "height", suppressEvent: true, supercedes: ["context", "fixedcenter", "iframe"] }, "ZINDEX": { key: "zindex", value: null }, "CONSTRAIN_TO_VIEWPORT": { key: "constraintoviewport", value: false, validator: Lang.isBoolean, supercedes: ["iframe", "x", "y", "xy"] }, "IFRAME": { key: "iframe", value: (YAHOO.env.ua.ie == 6 ? true : false), validator: Lang.isBoolean, supercedes: ["zindex"]} }; Overlay.IFRAME_SRC = "javascript:false;"; Overlay.IFRAME_OFFSET = 3; Overlay.TOP_LEFT = "tl"; Overlay.TOP_RIGHT = "tr"; Overlay.BOTTOM_LEFT = "bl"; Overlay.BOTTOM_RIGHT = "br"; Overlay.CSS_OVERLAY = "yui-overlay"; Overlay.windowScrollEvent = new CustomEvent("windowScroll"); Overlay.windowResizeEvent = new CustomEvent("windowResize"); Overlay.windowScrollHandler = function (e) { if (YAHOO.env.ua.ie) { if (!window.scrollEnd) { window.scrollEnd = -1; } clearTimeout(window.scrollEnd); window.scrollEnd = setTimeout(function () { Overlay.windowScrollEvent.fire(); }, 1); } else { Overlay.windowScrollEvent.fire(); } }; Overlay.windowResizeHandler = function (e) { if (YAHOO.env.ua.ie) { if (!window.resizeEnd) { window.resizeEnd = -1; } clearTimeout(window.resizeEnd); window.resizeEnd = setTimeout(function () { Overlay.windowResizeEvent.fire(); }, 100); } else { Overlay.windowResizeEvent.fire(); } }; Overlay._initialized = null; if (Overlay._initialized === null) { Event.on(window, "scroll", Overlay.windowScrollHandler); Event.on(window, "resize", Overlay.windowResizeHandler); Overlay._initialized = true; } YAHOO.extend(Overlay, Module, { init: function (el, userConfig) { Overlay.superclass.init.call(this, el); this.beforeInitEvent.fire(Overlay); Dom.addClass(this.element, Overlay.CSS_OVERLAY); if (userConfig) { this.cfg.applyConfig(userConfig, true); } if (this.platform == "mac" && YAHOO.env.ua.gecko) { if (!Config.alreadySubscribed(this.showEvent, this.showMacGeckoScrollbars, this)) { this.showEvent.subscribe(this.showMacGeckoScrollbars, this, true); } if (!Config.alreadySubscribed(this.hideEvent, this.hideMacGeckoScrollbars, this)) { this.hideEvent.subscribe(this.hideMacGeckoScrollbars, this, true); } } this.initEvent.fire(Overlay); }, initEvents: function () { Overlay.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; this.beforeMoveEvent = this.createEvent(EVENT_TYPES.BEFORE_MOVE); this.beforeMoveEvent.signature = SIGNATURE; this.moveEvent = this.createEvent(EVENT_TYPES.MOVE); this.moveEvent.signature = SIGNATURE; }, initDefaultConfig: function () { Overlay.superclass.initDefaultConfig.call(this); this.cfg.addProperty(DEFAULT_CONFIG.X.key, { handler: this.configX, validator: DEFAULT_CONFIG.X.validator, suppressEvent: DEFAULT_CONFIG.X.suppressEvent, supercedes: DEFAULT_CONFIG.X.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.Y.key, { handler: this.configY, validator: DEFAULT_CONFIG.Y.validator, suppressEvent: DEFAULT_CONFIG.Y.suppressEvent, supercedes: DEFAULT_CONFIG.Y.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.XY.key, { handler: this.configXY, suppressEvent: DEFAULT_CONFIG.XY.suppressEvent, supercedes: DEFAULT_CONFIG.XY.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.CONTEXT.key, { handler: this.configContext, suppressEvent: DEFAULT_CONFIG.CONTEXT.suppressEvent, supercedes: DEFAULT_CONFIG.CONTEXT.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.FIXED_CENTER.key, { handler: this.configFixedCenter, value: DEFAULT_CONFIG.FIXED_CENTER.value, validator: DEFAULT_CONFIG.FIXED_CENTER.validator, supercedes: DEFAULT_CONFIG.FIXED_CENTER.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.WIDTH.key, { handler: this.configWidth, suppressEvent: DEFAULT_CONFIG.WIDTH.suppressEvent, supercedes: DEFAULT_CONFIG.WIDTH.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.HEIGHT.key, { handler: this.configHeight, suppressEvent: DEFAULT_CONFIG.HEIGHT.suppressEvent, supercedes: DEFAULT_CONFIG.HEIGHT.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.ZINDEX.key, { handler: this.configzIndex, value: DEFAULT_CONFIG.ZINDEX.value }); this.cfg.addProperty(DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.key, { handler: this.configConstrainToViewport, value: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.value, validator: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.validator, supercedes: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.IFRAME.key, { handler: this.configIframe, value: DEFAULT_CONFIG.IFRAME.value, validator: DEFAULT_CONFIG.IFRAME.validator, supercedes: DEFAULT_CONFIG.IFRAME.supercedes }); }, moveTo: function (x, y) { this.cfg.setProperty("xy", [x, y]); }, hideMacGeckoScrollbars: function () { Dom.removeClass(this.element, "show-scrollbars"); Dom.addClass(this.element, "hide-scrollbars"); }, showMacGeckoScrollbars: function () { Dom.removeClass(this.element, "hide-scrollbars"); Dom.addClass(this.element, "show-scrollbars"); }, configVisible: function (type, args, obj) { var visible = args[0], currentVis = Dom.getStyle(this.element, "visibility"), effect = this.cfg.getProperty("effect"), effectInstances = [], isMacGecko = (this.platform == "mac" && YAHOO.env.ua.gecko), alreadySubscribed = Config.alreadySubscribed, eff, ei, e, i, j, k, h, nEffects, nEffectInstances; if (currentVis == "inherit") { e = this.element.parentNode; while (e.nodeType != 9 && e.nodeType != 11) { currentVis = Dom.getStyle(e, "visibility"); if (currentVis != "inherit") { break; } e = e.parentNode; } if (currentVis == "inherit") { currentVis = "visible"; } } if (effect) { if (effect instanceof Array) { nEffects = effect.length; for (i = 0; i < nEffects; i++) { eff = effect[i]; effectInstances[effectInstances.length] = eff.effect(this, eff.duration); } } else { effectInstances[effectInstances.length] = effect.effect(this, effect.duration); } } if (visible) { if (isMacGecko) { this.showMacGeckoScrollbars(); } if (effect) { if (visible) { if (currentVis != "visible" || currentVis === "") { this.beforeShowEvent.fire(); nEffectInstances = effectInstances.length; for (j = 0; j < nEffectInstances; j++) { ei = effectInstances[j]; if (j === 0 && !alreadySubscribed(ei.animateInCompleteEvent, this.showEvent.fire, this.showEvent)) { ei.animateInCompleteEvent.subscribe(this.showEvent.fire, this.showEvent, true); } ei.animateIn(); } } } } else { if (currentVis != "visible" || currentVis === "") { this.beforeShowEvent.fire(); Dom.setStyle(this.element, "visibility", "visible"); this.cfg.refireEvent("iframe"); this.showEvent.fire(); } } } else { if (isMacGecko) { this.hideMacGeckoScrollbars(); } if (effect) { if (currentVis == "visible") { this.beforeHideEvent.fire(); nEffectInstances = effectInstances.length; for (k = 0; k < nEffectInstances; k++) { h = effectInstances[k]; if (k === 0 && !alreadySubscribed(h.animateOutCompleteEvent, this.hideEvent.fire, this.hideEvent)) { h.animateOutCompleteEvent.subscribe(this.hideEvent.fire, this.hideEvent, true); } h.animateOut(); } } else { if (currentVis === "") { Dom.setStyle(this.element, "visibility", "hidden"); } } } else { if (currentVis == "visible" || currentVis === "") { this.beforeHideEvent.fire(); Dom.setStyle(this.element, "visibility", "hidden"); this.hideEvent.fire(); } } } }, doCenterOnDOMEvent: function () { if (this.cfg.getProperty("visible")) { this.center(); } }, configFixedCenter: function (type, args, obj) { var val = args[0], alreadySubscribed = Config.alreadySubscribed, windowResizeEvent = Overlay.windowResizeEvent, windowScrollEvent = Overlay.windowScrollEvent; if (val) { this.center(); if (!alreadySubscribed(this.beforeShowEvent, this.center, this)) { this.beforeShowEvent.subscribe(this.center); } if (!alreadySubscribed(windowResizeEvent, this.doCenterOnDOMEvent, this)) { windowResizeEvent.subscribe(this.doCenterOnDOMEvent, this, true); } if (!alreadySubscribed(windowScrollEvent, this.doCenterOnDOMEvent, this)) { windowScrollEvent.subscribe(this.doCenterOnDOMEvent, this, true); } } else { this.beforeShowEvent.unsubscribe(this.center); windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this); windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this); } }, configHeight: function (type, args, obj) { var height = args[0], el = this.element; Dom.setStyle(el, "height", height); this.cfg.refireEvent("iframe"); }, configWidth: function (type, args, obj) { var width = args[0], el = this.element; Dom.setStyle(el, "width", width); this.cfg.refireEvent("iframe"); }, configzIndex: function (type, args, obj) { var zIndex = args[0], el = this.element; if (!zIndex) { zIndex = Dom.getStyle(el, "zIndex"); if (!zIndex || isNaN(zIndex)) { zIndex = 0; } } if (this.iframe || this.cfg.getProperty("iframe") === true) { if (zIndex <= 0) { zIndex = 1; } } Dom.setStyle(el, "zIndex", zIndex); this.cfg.setProperty("zIndex", zIndex, true); if (this.iframe) { this.stackIframe(); } }, configXY: function (type, args, obj) { var pos = args[0], x = pos[0], y = pos[1]; this.cfg.setProperty("x", x); this.cfg.setProperty("y", y); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, configX: function (type, args, obj) { var x = args[0], y = this.cfg.getProperty("y"); this.cfg.setProperty("x", x, true); this.cfg.setProperty("y", y, true); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); Dom.setX(this.element, x, true); this.cfg.setProperty("xy", [x, y], true); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, configY: function (type, args, obj) { var x = this.cfg.getProperty("x"), y = args[0]; this.cfg.setProperty("x", x, true); this.cfg.setProperty("y", y, true); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); Dom.setY(this.element, y, true); this.cfg.setProperty("xy", [x, y], true); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, showIframe: function () { var oIFrame = this.iframe, oParentNode; if (oIFrame) { oParentNode = this.element.parentNode; if (oParentNode != oIFrame.parentNode) { this._addToParent(oParentNode, oIFrame); } oIFrame.style.display = "block"; } }, hideIframe: function () { if (this.iframe) { this.iframe.style.display = "none"; } }, syncIframe: function () { var oIFrame = this.iframe, oElement = this.element, nOffset = Overlay.IFRAME_OFFSET, nDimensionOffset = (nOffset * 2), aXY; if (oIFrame) { oIFrame.style.width = (oElement.offsetWidth + nDimensionOffset + "px"); oIFrame.style.height = (oElement.offsetHeight + nDimensionOffset + "px"); aXY = this.cfg.getProperty("xy"); if (!Lang.isArray(aXY) || (isNaN(aXY[0]) || isNaN(aXY[1]))) { this.syncPosition(); aXY = this.cfg.getProperty("xy"); } Dom.setXY(oIFrame, [(aXY[0] - nOffset), (aXY[1] - nOffset)]); } }, stackIframe: function () { if (this.iframe) { var overlayZ = Dom.getStyle(this.element, "zIndex"); if (!YAHOO.lang.isUndefined(overlayZ) && !isNaN(overlayZ)) { Dom.setStyle(this.iframe, "zIndex", (overlayZ - 1)); } } }, configIframe: function (type, args, obj) { var bIFrame = args[0]; function createIFrame() { var oIFrame = this.iframe, oElement = this.element, oParent, aXY; if (!oIFrame) { if (!m_oIFrameTemplate) { m_oIFrameTemplate = document.createElement("iframe"); if (this.isSecure) { m_oIFrameTemplate.src = Overlay.IFRAME_SRC; } if (YAHOO.env.ua.ie) { m_oIFrameTemplate.style.filter = "alpha(opacity=0)"; m_oIFrameTemplate.frameBorder = 0; } else { m_oIFrameTemplate.style.opacity = "0"; } m_oIFrameTemplate.style.position = "absolute"; m_oIFrameTemplate.style.border = "none"; m_oIFrameTemplate.style.margin = "0"; m_oIFrameTemplate.style.padding = "0"; m_oIFrameTemplate.style.display = "none"; } oIFrame = m_oIFrameTemplate.cloneNode(false); oParent = oElement.parentNode; var parentNode = oParent || document.body; this._addToParent(parentNode, oIFrame); this.iframe = oIFrame; } this.showIframe(); this.syncIframe(); this.stackIframe(); if (!this._hasIframeEventListeners) { this.showEvent.subscribe(this.showIframe); this.hideEvent.subscribe(this.hideIframe); this.changeContentEvent.subscribe(this.syncIframe); this._hasIframeEventListeners = true; } } function onBeforeShow() { createIFrame.call(this); this.beforeShowEvent.unsubscribe(onBeforeShow); this._iframeDeferred = false; } if (bIFrame) { if (this.cfg.getProperty("visible")) { createIFrame.call(this); } else { if (!this._iframeDeferred) { this.beforeShowEvent.subscribe(onBeforeShow); this._iframeDeferred = true; } } } else { this.hideIframe(); if (this._hasIframeEventListeners) { this.showEvent.unsubscribe(this.showIframe); this.hideEvent.unsubscribe(this.hideIframe); this.changeContentEvent.unsubscribe(this.syncIframe); this._hasIframeEventListeners = false; } } }, configConstrainToViewport: function (type, args, obj) { var val = args[0]; if (val) { if (!Config.alreadySubscribed(this.beforeMoveEvent, this.enforceConstraints, this)) { this.beforeMoveEvent.subscribe(this.enforceConstraints, this, true); } } else { this.beforeMoveEvent.unsubscribe(this.enforceConstraints, this); } }, configContext: function (type, args, obj) { var contextArgs = args[0], contextEl, elementMagnetCorner, contextMagnetCorner; if (contextArgs) { contextEl = contextArgs[0]; elementMagnetCorner = contextArgs[1]; contextMagnetCorner = contextArgs[2]; if (contextEl) { if (typeof contextEl == "string") { this.cfg.setProperty("context", [document.getElementById(contextEl), elementMagnetCorner, contextMagnetCorner], true); } if (elementMagnetCorner && contextMagnetCorner) { this.align(elementMagnetCorner, contextMagnetCorner); } } } }, align: function (elementAlign, contextAlign) { var contextArgs = this.cfg.getProperty("context"), me = this, context, element, contextRegion; function doAlign(v, h) { switch (elementAlign) { case Overlay.TOP_LEFT: me.moveTo(h, v); break; case Overlay.TOP_RIGHT: me.moveTo((h - element.offsetWidth), v); break; case Overlay.BOTTOM_LEFT: me.moveTo(h, (v - element.offsetHeight)); break; case Overlay.BOTTOM_RIGHT: me.moveTo((h - element.offsetWidth), (v - element.offsetHeight)); break; } } if (contextArgs) { context = contextArgs[0]; element = this.element; me = this; if (!elementAlign) { elementAlign = contextArgs[1]; } if (!contextAlign) { contextAlign = contextArgs[2]; } if (element && context) { contextRegion = Dom.getRegion(context); switch (contextAlign) { case Overlay.TOP_LEFT: doAlign(contextRegion.top, contextRegion.left); break; case Overlay.TOP_RIGHT: doAlign(contextRegion.top, contextRegion.right); break; case Overlay.BOTTOM_LEFT: doAlign(contextRegion.bottom, contextRegion.left); break; case Overlay.BOTTOM_RIGHT: doAlign(contextRegion.bottom, contextRegion.right); break; } } } }, enforceConstraints: function (type, args, obj) { var pos = args[0], x = pos[0], y = pos[1], offsetHeight = this.element.offsetHeight, offsetWidth = this.element.offsetWidth, viewPortWidth = Dom.getViewportWidth(), viewPortHeight = Dom.getViewportHeight(), scrollX = Dom.getDocumentScrollLeft(), scrollY = Dom.getDocumentScrollTop(), topConstraint = scrollY + 10, leftConstraint = scrollX + 10, bottomConstraint = scrollY + viewPortHeight - offsetHeight - 10, rightConstraint = scrollX + viewPortWidth - offsetWidth - 10; if (x < leftConstraint) { x = leftConstraint; } else { if (x > rightConstraint) { x = rightConstraint; } } if (y < topConstraint) { y = topConstraint; } else { if (y > bottomConstraint) { y = bottomConstraint; } } this.cfg.setProperty("x", x, true); this.cfg.setProperty("y", y, true); this.cfg.setProperty("xy", [x, y], true); }, center: function () { var scrollX = Dom.getDocumentScrollLeft(), scrollY = Dom.getDocumentScrollTop(), viewPortWidth = Dom.getClientWidth(), viewPortHeight = Dom.getClientHeight(), elementWidth = this.element.offsetWidth, elementHeight = this.element.offsetHeight, x = (viewPortWidth / 2) - (elementWidth / 2) + scrollX, y = (viewPortHeight / 2) - (elementHeight / 2) + scrollY; this.cfg.setProperty("xy", [parseInt(x, 10), parseInt(y, 10)]); this.cfg.refireEvent("iframe"); }, syncPosition: function () { var pos = Dom.getXY(this.element); this.cfg.setProperty("x", pos[0], true); this.cfg.setProperty("y", pos[1], true); this.cfg.setProperty("xy", pos, true); }, onDomResize: function (e, obj) { var me = this; Overlay.superclass.onDomResize.call(this, e, obj); setTimeout(function () { me.syncPosition(); me.cfg.refireEvent("iframe"); me.cfg.refireEvent("context"); }, 0); }, bringToTop: function () { var aOverlays = [], oElement = this.element; function compareZIndexDesc(p_oOverlay1, p_oOverlay2) { var sZIndex1 = Dom.getStyle(p_oOverlay1, "zIndex"), sZIndex2 = Dom.getStyle(p_oOverlay2, "zIndex"), nZIndex1 = (!sZIndex1 || isNaN(sZIndex1)) ? 0 : parseInt(sZIndex1, 10), nZIndex2 = (!sZIndex2 || isNaN(sZIndex2)) ? 0 : parseInt(sZIndex2, 10); if (nZIndex1 > nZIndex2) { return -1; } else { if (nZIndex1 < nZIndex2) { return 1; } else { return 0; } } } function isOverlayElement(p_oElement) { var oOverlay = Dom.hasClass(p_oElement, Overlay.CSS_OVERLAY), Panel = YAHOO.widget.Panel; if (oOverlay && !Dom.isAncestor(oElement, oOverlay)) { if (Panel && Dom.hasClass(p_oElement, Panel.CSS_PANEL)) { aOverlays[aOverlays.length] = p_oElement.parentNode; } else { aOverlays[aOverlays.length] = p_oElement; } } } Dom.getElementsBy(isOverlayElement, "DIV", document.body); aOverlays.sort(compareZIndexDesc); var oTopOverlay = aOverlays[0], nTopZIndex; if (oTopOverlay) { nTopZIndex = Dom.getStyle(oTopOverlay, "zIndex"); if (!isNaN(nTopZIndex) && oTopOverlay != oElement) { this.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2)); } } }, destroy: function () { if (this.iframe) { this.iframe.parentNode.removeChild(this.iframe); } this.iframe = null; Overlay.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this); Overlay.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this); Overlay.superclass.destroy.call(this); }, toString: function () { return "Overlay " + this.id; } }); } ()); (function () { YAHOO.widget.OverlayManager = function (userConfig) { this.init(userConfig); }; var Overlay = YAHOO.widget.Overlay, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, CustomEvent = YAHOO.util.CustomEvent, OverlayManager = YAHOO.widget.OverlayManager; OverlayManager.CSS_FOCUSED = "focused"; OverlayManager.prototype = { constructor: OverlayManager, overlays: null, initDefaultConfig: function () { this.cfg.addProperty("overlays", { suppressEvent: true }); this.cfg.addProperty("focusevent", { value: "mousedown" }); }, init: function (userConfig) { this.cfg = new Config(this); this.initDefaultConfig(); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.cfg.fireQueue(); var activeOverlay = null; this.getActive = function () { return activeOverlay; }; this.focus = function (overlay) { var o = this.find(overlay); if (o) { if (activeOverlay != o) { if (activeOverlay) { activeOverlay.blur(); } this.bringToTop(o); activeOverlay = o; Dom.addClass(activeOverlay.element, OverlayManager.CSS_FOCUSED); o.focusEvent.fire(); } } }; this.remove = function (overlay) { var o = this.find(overlay), originalZ; if (o) { if (activeOverlay == o) { activeOverlay = null; } var bDestroyed = (o.element === null && o.cfg === null) ? true : false; if (!bDestroyed) { originalZ = Dom.getStyle(o.element, "zIndex"); o.cfg.setProperty("zIndex", -1000, true); } this.overlays.sort(this.compareZIndexDesc); this.overlays = this.overlays.slice(0, (this.overlays.length - 1)); o.hideEvent.unsubscribe(o.blur); o.destroyEvent.unsubscribe(this._onOverlayDestroy, o); if (!bDestroyed) { Event.removeListener(o.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus); o.cfg.setProperty("zIndex", originalZ, true); o.cfg.setProperty("manager", null); } o.focusEvent.unsubscribeAll(); o.blurEvent.unsubscribeAll(); o.focusEvent = null; o.blurEvent = null; o.focus = null; o.blur = null; } }; this.blurAll = function () { var nOverlays = this.overlays.length, i; if (nOverlays > 0) { i = nOverlays - 1; do { this.overlays[i].blur(); } while (i--); } }; this._onOverlayBlur = function (p_sType, p_aArgs) { activeOverlay = null; }; var overlays = this.cfg.getProperty("overlays"); if (!this.overlays) { this.overlays = []; } if (overlays) { this.register(overlays); this.overlays.sort(this.compareZIndexDesc); } }, _onOverlayElementFocus: function (p_oEvent) { var oTarget = Event.getTarget(p_oEvent), oClose = this.close; if (oClose && (oTarget == oClose || Dom.isAncestor(oClose, oTarget))) { this.blur(); } else { this.focus(); } }, _onOverlayDestroy: function (p_sType, p_aArgs, p_oOverlay) { this.remove(p_oOverlay); }, register: function (overlay) { var mgr = this, zIndex, regcount, i, nOverlays; if (overlay instanceof Overlay) { overlay.cfg.addProperty("manager", { value: this }); overlay.focusEvent = overlay.createEvent("focus"); overlay.focusEvent.signature = CustomEvent.LIST; overlay.blurEvent = overlay.createEvent("blur"); overlay.blurEvent.signature = CustomEvent.LIST; overlay.focus = function () { mgr.focus(this); }; overlay.blur = function () { if (mgr.getActive() == this) { Dom.removeClass(this.element, OverlayManager.CSS_FOCUSED); this.blurEvent.fire(); } }; overlay.blurEvent.subscribe(mgr._onOverlayBlur); overlay.hideEvent.subscribe(overlay.blur); overlay.destroyEvent.subscribe(this._onOverlayDestroy, overlay, this); Event.on(overlay.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus, null, overlay); zIndex = Dom.getStyle(overlay.element, "zIndex"); if (!isNaN(zIndex)) { overlay.cfg.setProperty("zIndex", parseInt(zIndex, 10)); } else { overlay.cfg.setProperty("zIndex", 0); } this.overlays.push(overlay); this.bringToTop(overlay); return true; } else { if (overlay instanceof Array) { regcount = 0; nOverlays = overlay.length; for (i = 0; i < nOverlays; i++) { if (this.register(overlay[i])) { regcount++; } } if (regcount > 0) { return true; } } else { return false; } } }, bringToTop: function (p_oOverlay) { var oOverlay = this.find(p_oOverlay), nTopZIndex, oTopOverlay, aOverlays; if (oOverlay) { aOverlays = this.overlays; aOverlays.sort(this.compareZIndexDesc); oTopOverlay = aOverlays[0]; if (oTopOverlay) { nTopZIndex = Dom.getStyle(oTopOverlay.element, "zIndex"); if (!isNaN(nTopZIndex) && oTopOverlay != oOverlay) { oOverlay.cfg.setProperty("zIndex", (parseInt(nTopZIndex, 10) + 2)); } aOverlays.sort(this.compareZIndexDesc); } } }, find: function (overlay) { var aOverlays = this.overlays, nOverlays = aOverlays.length, i; if (nOverlays > 0) { i = nOverlays - 1; if (overlay instanceof Overlay) { do { if (aOverlays[i] == overlay) { return aOverlays[i]; } } while (i--); } else { if (typeof overlay == "string") { do { if (aOverlays[i].id == overlay) { return aOverlays[i]; } } while (i--); } } return null; } }, compareZIndexDesc: function (o1, o2) { var zIndex1 = (o1.cfg) ? o1.cfg.getProperty("zIndex") : null, zIndex2 = (o2.cfg) ? o2.cfg.getProperty("zIndex") : null; if (zIndex1 === null && zIndex2 === null) { return 0; } else { if (zIndex1 === null) { return 1; } else { if (zIndex2 === null) { return -1; } else { if (zIndex1 > zIndex2) { return -1; } else { if (zIndex1 < zIndex2) { return 1; } else { return 0; } } } } } }, showAll: function () { var aOverlays = this.overlays, nOverlays = aOverlays.length, i; if (nOverlays > 0) { i = nOverlays - 1; do { aOverlays[i].show(); } while (i--); } }, hideAll: function () { var aOverlays = this.overlays, nOverlays = aOverlays.length, i; if (nOverlays > 0) { i = nOverlays - 1; do { aOverlays[i].hide(); } while (i--); } }, toString: function () { return "OverlayManager"; } }; } ()); (function () { YAHOO.widget.Tooltip = function (el, userConfig) { YAHOO.widget.Tooltip.superclass.constructor.call(this, el, userConfig); }; var Lang = YAHOO.lang, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Tooltip = YAHOO.widget.Tooltip, m_oShadowTemplate, DEFAULT_CONFIG = { "PREVENT_OVERLAP": { key: "preventoverlap", value: true, validator: Lang.isBoolean, supercedes: ["x", "y", "xy"] }, "SHOW_DELAY": { key: "showdelay", value: 200, validator: Lang.isNumber }, "AUTO_DISMISS_DELAY": { key: "autodismissdelay", value: 5000, validator: Lang.isNumber }, "HIDE_DELAY": { key: "hidedelay", value: 250, validator: Lang.isNumber }, "TEXT": { key: "text", suppressEvent: true }, "CONTAINER": { key: "container"} }; Tooltip.CSS_TOOLTIP = "yui-tt"; function restoreOriginalWidth(p_sType, p_aArgs, p_oObject) { var sOriginalWidth = p_oObject[0], sNewWidth = p_oObject[1], oConfig = this.cfg, sCurrentWidth = oConfig.getProperty("width"); if (sCurrentWidth == sNewWidth) { oConfig.setProperty("width", sOriginalWidth); } this.unsubscribe("hide", this._onHide, p_oObject); } function setWidthToOffsetWidth(p_sType, p_aArgs) { var oBody = document.body, oConfig = this.cfg, sOriginalWidth = oConfig.getProperty("width"), sNewWidth, oClone; if ((!sOriginalWidth || sOriginalWidth == "auto") && (oConfig.getProperty("container") != oBody || oConfig.getProperty("x") >= Dom.getViewportWidth() || oConfig.getProperty("y") >= Dom.getViewportHeight())) { oClone = this.element.cloneNode(true); oClone.style.visibility = "hidden"; oClone.style.top = "0px"; oClone.style.left = "0px"; oBody.appendChild(oClone); sNewWidth = (oClone.offsetWidth + "px"); oBody.removeChild(oClone); oClone = null; oConfig.setProperty("width", sNewWidth); oConfig.refireEvent("xy"); this.subscribe("hide", restoreOriginalWidth, [(sOriginalWidth || ""), sNewWidth]); } } function onDOMReady(p_sType, p_aArgs, p_oObject) { this.render(p_oObject); } function onInit() { Event.onDOMReady(onDOMReady, this.cfg.getProperty("container"), this); } YAHOO.extend(Tooltip, YAHOO.widget.Overlay, { init: function (el, userConfig) { Tooltip.superclass.init.call(this, el); this.beforeInitEvent.fire(Tooltip); Dom.addClass(this.element, Tooltip.CSS_TOOLTIP); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.cfg.queueProperty("visible", false); this.cfg.queueProperty("constraintoviewport", true); this.setBody(""); this.subscribe("beforeShow", setWidthToOffsetWidth); this.subscribe("init", onInit); this.subscribe("render", this.onRender); this.initEvent.fire(Tooltip); }, initDefaultConfig: function () { Tooltip.superclass.initDefaultConfig.call(this); this.cfg.addProperty(DEFAULT_CONFIG.PREVENT_OVERLAP.key, { value: DEFAULT_CONFIG.PREVENT_OVERLAP.value, validator: DEFAULT_CONFIG.PREVENT_OVERLAP.validator, supercedes: DEFAULT_CONFIG.PREVENT_OVERLAP.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.SHOW_DELAY.key, { handler: this.configShowDelay, value: 200, validator: DEFAULT_CONFIG.SHOW_DELAY.validator }); this.cfg.addProperty(DEFAULT_CONFIG.AUTO_DISMISS_DELAY.key, { handler: this.configAutoDismissDelay, value: DEFAULT_CONFIG.AUTO_DISMISS_DELAY.value, validator: DEFAULT_CONFIG.AUTO_DISMISS_DELAY.validator }); this.cfg.addProperty(DEFAULT_CONFIG.HIDE_DELAY.key, { handler: this.configHideDelay, value: DEFAULT_CONFIG.HIDE_DELAY.value, validator: DEFAULT_CONFIG.HIDE_DELAY.validator }); this.cfg.addProperty(DEFAULT_CONFIG.TEXT.key, { handler: this.configText, suppressEvent: DEFAULT_CONFIG.TEXT.suppressEvent }); this.cfg.addProperty(DEFAULT_CONFIG.CONTAINER.key, { handler: this.configContainer, value: document.body }); }, configText: function (type, args, obj) { var text = args[0]; if (text) { this.setBody(text); } }, configContainer: function (type, args, obj) { var container = args[0]; if (typeof container == "string") { this.cfg.setProperty("container", document.getElementById(container), true); } }, _removeEventListeners: function () { var aElements = this._context, nElements, oElement, i; if (aElements) { nElements = aElements.length; if (nElements > 0) { i = nElements - 1; do { oElement = aElements[i]; Event.removeListener(oElement, "mouseover", this.onContextMouseOver); Event.removeListener(oElement, "mousemove", this.onContextMouseMove); Event.removeListener(oElement, "mouseout", this.onContextMouseOut); } while (i--); } } }, configContext: function (type, args, obj) { var context = args[0], aElements, nElements, oElement, i; if (context) { if (!(context instanceof Array)) { if (typeof context == "string") { this.cfg.setProperty("context", [document.getElementById(context)], true); } else { this.cfg.setProperty("context", [context], true); } context = this.cfg.getProperty("context"); } this._removeEventListeners(); this._context = context; aElements = this._context; if (aElements) { nElements = aElements.length; if (nElements > 0) { i = nElements - 1; do { oElement = aElements[i]; Event.on(oElement, "mouseover", this.onContextMouseOver, this); Event.on(oElement, "mousemove", this.onContextMouseMove, this); Event.on(oElement, "mouseout", this.onContextMouseOut, this); } while (i--); } } } }, onContextMouseMove: function (e, obj) { obj.pageX = Event.getPageX(e); obj.pageY = Event.getPageY(e); }, onContextMouseOver: function (e, obj) { var context = this; if (obj.hideProcId) { clearTimeout(obj.hideProcId); obj.hideProcId = null; } Event.on(context, "mousemove", obj.onContextMouseMove, obj); if (context.title) { obj._tempTitle = context.title; context.title = ""; } obj.showProcId = obj.doShow(e, context); }, onContextMouseOut: function (e, obj) { var el = this; if (obj._tempTitle) { el.title = obj._tempTitle; obj._tempTitle = null; } if (obj.showProcId) { clearTimeout(obj.showProcId); obj.showProcId = null; } if (obj.hideProcId) { clearTimeout(obj.hideProcId); obj.hideProcId = null; } obj.hideProcId = setTimeout(function () { obj.hide(); }, obj.cfg.getProperty("hidedelay")); }, doShow: function (e, context) { var yOffset = 25, me = this; if (YAHOO.env.ua.opera && context.tagName && context.tagName.toUpperCase() == "A") { yOffset += 12; } return setTimeout(function () { if (me._tempTitle) { me.setBody(me._tempTitle); } else { me.cfg.refireEvent("text"); } me.moveTo(me.pageX, me.pageY + yOffset); if (me.cfg.getProperty("preventoverlap")) { me.preventOverlap(me.pageX, me.pageY); } Event.removeListener(context, "mousemove", me.onContextMouseMove); me.show(); me.hideProcId = me.doHide(); }, this.cfg.getProperty("showdelay")); }, doHide: function () { var me = this; return setTimeout(function () { me.hide(); }, this.cfg.getProperty("autodismissdelay")); }, preventOverlap: function (pageX, pageY) { var height = this.element.offsetHeight, mousePoint = new YAHOO.util.Point(pageX, pageY), elementRegion = Dom.getRegion(this.element); elementRegion.top -= 5; elementRegion.left -= 5; elementRegion.right += 5; elementRegion.bottom += 5; if (elementRegion.contains(mousePoint)) { this.cfg.setProperty("y", (pageY - height - 5)); } }, onRender: function (p_sType, p_aArgs) { function sizeShadow() { var oElement = this.element, oShadow = this._shadow; if (oShadow) { oShadow.style.width = (oElement.offsetWidth + 6) + "px"; oShadow.style.height = (oElement.offsetHeight + 1) + "px"; } } function addShadowVisibleClass() { Dom.addClass(this._shadow, "yui-tt-shadow-visible"); } function removeShadowVisibleClass() { Dom.removeClass(this._shadow, "yui-tt-shadow-visible"); } function createShadow() { var oShadow = this._shadow, oElement, Module, nIE, me; if (!oShadow) { oElement = this.element; Module = YAHOO.widget.Module; nIE = YAHOO.env.ua.ie; me = this; if (!m_oShadowTemplate) { m_oShadowTemplate = document.createElement("div"); m_oShadowTemplate.className = "yui-tt-shadow"; } oShadow = m_oShadowTemplate.cloneNode(false); oElement.appendChild(oShadow); this._shadow = oShadow; addShadowVisibleClass.call(this); this.subscribe("beforeShow", addShadowVisibleClass); this.subscribe("beforeHide", removeShadowVisibleClass); if (nIE == 6 || (nIE == 7 && document.compatMode == "BackCompat")) { window.setTimeout(function () { sizeShadow.call(me); }, 0); this.cfg.subscribeToConfigEvent("width", sizeShadow); this.cfg.subscribeToConfigEvent("height", sizeShadow); this.subscribe("changeContent", sizeShadow); Module.textResizeEvent.subscribe(sizeShadow, this, true); this.subscribe("destroy", function () { Module.textResizeEvent.unsubscribe(sizeShadow, this); }); } } } function onBeforeShow() { createShadow.call(this); this.unsubscribe("beforeShow", onBeforeShow); } if (this.cfg.getProperty("visible")) { createShadow.call(this); } else { this.subscribe("beforeShow", onBeforeShow); } }, destroy: function () { this._removeEventListeners(); Tooltip.superclass.destroy.call(this); }, toString: function () { return "Tooltip " + this.id; } }); } ()); (function () { YAHOO.widget.Panel = function (el, userConfig) { YAHOO.widget.Panel.superclass.constructor.call(this, el, userConfig); }; var Lang = YAHOO.lang, DD = YAHOO.util.DD, Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Overlay = YAHOO.widget.Overlay, CustomEvent = YAHOO.util.CustomEvent, Config = YAHOO.util.Config, Panel = YAHOO.widget.Panel, m_oMaskTemplate, m_oUnderlayTemplate, m_oCloseIconTemplate, EVENT_TYPES = { "SHOW_MASK": "showMask", "HIDE_MASK": "hideMask", "DRAG": "drag" }, DEFAULT_CONFIG = { "CLOSE": { key: "close", value: true, validator: Lang.isBoolean, supercedes: ["visible"] }, "DRAGGABLE": { key: "draggable", value: (DD ? true : false), validator: Lang.isBoolean, supercedes: ["visible"] }, "UNDERLAY": { key: "underlay", value: "shadow", supercedes: ["visible"] }, "MODAL": { key: "modal", value: false, validator: Lang.isBoolean, supercedes: ["visible", "zindex"] }, "KEY_LISTENERS": { key: "keylisteners", suppressEvent: true, supercedes: ["visible"]} }; Panel.CSS_PANEL = "yui-panel"; Panel.CSS_PANEL_CONTAINER = "yui-panel-container"; function createHeader(p_sType, p_aArgs) { if (!this.header) { this.setHeader("&#160;"); } } function restoreOriginalWidth(p_sType, p_aArgs, p_oObject) { var sOriginalWidth = p_oObject[0], sNewWidth = p_oObject[1], oConfig = this.cfg, sCurrentWidth = oConfig.getProperty("width"); if (sCurrentWidth == sNewWidth) { oConfig.setProperty("width", sOriginalWidth); } this.unsubscribe("hide", restoreOriginalWidth, p_oObject); } function setWidthToOffsetWidth(p_sType, p_aArgs) { var nIE = YAHOO.env.ua.ie, oConfig, sOriginalWidth, sNewWidth; if (nIE == 6 || (nIE == 7 && document.compatMode == "BackCompat")) { oConfig = this.cfg; sOriginalWidth = oConfig.getProperty("width"); if (!sOriginalWidth || sOriginalWidth == "auto") { sNewWidth = (this.element.offsetWidth + "px"); oConfig.setProperty("width", sNewWidth); this.subscribe("hide", restoreOriginalWidth, [(sOriginalWidth || ""), sNewWidth]); } } } function onElementFocus() { this.blur(); } function addFocusEventHandlers(p_sType, p_aArgs) { var me = this; function isFocusable(el) { var sTagName = el.tagName.toUpperCase(), bFocusable = false; switch (sTagName) { case "A": case "BUTTON": case "SELECT": case "TEXTAREA": if (!Dom.isAncestor(me.element, el)) { Event.on(el, "focus", onElementFocus, el, true); bFocusable = true; } break; case "INPUT": if (el.type != "hidden" && !Dom.isAncestor(me.element, el)) { Event.on(el, "focus", onElementFocus, el, true); bFocusable = true; } break; } return bFocusable; } this.focusableElements = Dom.getElementsBy(isFocusable); } function removeFocusEventHandlers(p_sType, p_aArgs) { var aElements = this.focusableElements, nElements = aElements.length, el2, i; for (i = 0; i < nElements; i++) { el2 = aElements[i]; Event.removeListener(el2, "focus", onElementFocus); } } YAHOO.extend(Panel, Overlay, { init: function (el, userConfig) { Panel.superclass.init.call(this, el); this.beforeInitEvent.fire(Panel); Dom.addClass(this.element, Panel.CSS_PANEL); this.buildWrapper(); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.subscribe("showMask", addFocusEventHandlers); this.subscribe("hideMask", removeFocusEventHandlers); if (this.cfg.getProperty("draggable")) { this.subscribe("beforeRender", createHeader); } this.initEvent.fire(Panel); }, initEvents: function () { Panel.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; this.showMaskEvent = this.createEvent(EVENT_TYPES.SHOW_MASK); this.showMaskEvent.signature = SIGNATURE; this.hideMaskEvent = this.createEvent(EVENT_TYPES.HIDE_MASK); this.hideMaskEvent.signature = SIGNATURE; this.dragEvent = this.createEvent(EVENT_TYPES.DRAG); this.dragEvent.signature = SIGNATURE; }, initDefaultConfig: function () { Panel.superclass.initDefaultConfig.call(this); this.cfg.addProperty(DEFAULT_CONFIG.CLOSE.key, { handler: this.configClose, value: DEFAULT_CONFIG.CLOSE.value, validator: DEFAULT_CONFIG.CLOSE.validator, supercedes: DEFAULT_CONFIG.CLOSE.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.DRAGGABLE.key, { handler: this.configDraggable, value: DEFAULT_CONFIG.DRAGGABLE.value, validator: DEFAULT_CONFIG.DRAGGABLE.validator, supercedes: DEFAULT_CONFIG.DRAGGABLE.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.UNDERLAY.key, { handler: this.configUnderlay, value: DEFAULT_CONFIG.UNDERLAY.value, supercedes: DEFAULT_CONFIG.UNDERLAY.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.MODAL.key, { handler: this.configModal, value: DEFAULT_CONFIG.MODAL.value, validator: DEFAULT_CONFIG.MODAL.validator, supercedes: DEFAULT_CONFIG.MODAL.supercedes }); this.cfg.addProperty(DEFAULT_CONFIG.KEY_LISTENERS.key, { handler: this.configKeyListeners, suppressEvent: DEFAULT_CONFIG.KEY_LISTENERS.suppressEvent, supercedes: DEFAULT_CONFIG.KEY_LISTENERS.supercedes }); }, configClose: function (type, args, obj) { var val = args[0], oClose = this.close; function doHide(e, obj) { obj.hide(); } if (val) { if (!oClose) { if (!m_oCloseIconTemplate) { m_oCloseIconTemplate = document.createElement("span"); m_oCloseIconTemplate.innerHTML = "&#160;"; m_oCloseIconTemplate.className = "container-close"; } oClose = m_oCloseIconTemplate.cloneNode(true); this.innerElement.appendChild(oClose); Event.on(oClose, "click", doHide, this); this.close = oClose; } else { oClose.style.display = "block"; } } else { if (oClose) { oClose.style.display = "none"; } } }, configDraggable: function (type, args, obj) { var val = args[0]; if (val) { if (!DD) { this.cfg.setProperty("draggable", false); return; } if (this.header) { Dom.setStyle(this.header, "cursor", "move"); this.registerDragDrop(); } if (!Config.alreadySubscribed(this.beforeRenderEvent, createHeader, null)) { this.subscribe("beforeRender", createHeader); } this.subscribe("beforeShow", setWidthToOffsetWidth); } else { if (this.dd) { this.dd.unreg(); } if (this.header) { Dom.setStyle(this.header, "cursor", "auto"); } this.unsubscribe("beforeRender", createHeader); this.unsubscribe("beforeShow", setWidthToOffsetWidth); } }, configUnderlay: function (type, args, obj) { var UA = YAHOO.env.ua, bMacGecko = (this.platform == "mac" && UA.gecko), sUnderlay = args[0].toLowerCase(), oUnderlay = this.underlay, oElement = this.element; function createUnderlay() { var nIE; if (!oUnderlay) { if (!m_oUnderlayTemplate) { m_oUnderlayTemplate = document.createElement("div"); m_oUnderlayTemplate.className = "underlay"; } oUnderlay = m_oUnderlayTemplate.cloneNode(false); this.element.appendChild(oUnderlay); this.underlay = oUnderlay; nIE = UA.ie; if (nIE == 6 || (nIE == 7 && document.compatMode == "BackCompat")) { this.sizeUnderlay(); this.cfg.subscribeToConfigEvent("width", this.sizeUnderlay); this.cfg.subscribeToConfigEvent("height", this.sizeUnderlay); this.changeContentEvent.subscribe(this.sizeUnderlay); YAHOO.widget.Module.textResizeEvent.subscribe(this.sizeUnderlay, this, true); } } } function onBeforeShow() { createUnderlay.call(this); this._underlayDeferred = false; this.beforeShowEvent.unsubscribe(onBeforeShow); } function destroyUnderlay() { if (this._underlayDeferred) { this.beforeShowEvent.unsubscribe(onBeforeShow); this._underlayDeferred = false; } if (oUnderlay) { this.cfg.unsubscribeFromConfigEvent("width", this.sizeUnderlay); this.cfg.unsubscribeFromConfigEvent("height", this.sizeUnderlay); this.changeContentEvent.unsubscribe(this.sizeUnderlay); YAHOO.widget.Module.textResizeEvent.unsubscribe(this.sizeUnderlay, this, true); this.element.removeChild(oUnderlay); this.underlay = null; } } switch (sUnderlay) { case "shadow": Dom.removeClass(oElement, "matte"); Dom.addClass(oElement, "shadow"); break; case "matte": if (!bMacGecko) { destroyUnderlay.call(this); } Dom.removeClass(oElement, "shadow"); Dom.addClass(oElement, "matte"); break; default: if (!bMacGecko) { destroyUnderlay.call(this); } Dom.removeClass(oElement, "shadow"); Dom.removeClass(oElement, "matte"); break; } if ((sUnderlay == "shadow") || (bMacGecko && !oUnderlay)) { if (this.cfg.getProperty("visible")) { createUnderlay.call(this); } else { if (!this._underlayDeferred) { this.beforeShowEvent.subscribe(onBeforeShow); this._underlayDeferred = true; } } } }, configModal: function (type, args, obj) { var modal = args[0]; if (modal) { if (!this._hasModalityEventListeners) { this.subscribe("beforeShow", this.buildMask); this.subscribe("beforeShow", this.bringToTop); this.subscribe("beforeShow", this.showMask); this.subscribe("hide", this.hideMask); Overlay.windowResizeEvent.subscribe(this.sizeMask, this, true); this._hasModalityEventListeners = true; } } else { if (this._hasModalityEventListeners) { if (this.cfg.getProperty("visible")) { this.hideMask(); this.removeMask(); } this.unsubscribe("beforeShow", this.buildMask); this.unsubscribe("beforeShow", this.bringToTop); this.unsubscribe("beforeShow", this.showMask); this.unsubscribe("hide", this.hideMask); Overlay.windowResizeEvent.unsubscribe(this.sizeMask, this); this._hasModalityEventListeners = false; } } }, removeMask: function () { var oMask = this.mask, oParentNode; if (oMask) { this.hideMask(); oParentNode = oMask.parentNode; if (oParentNode) { oParentNode.removeChild(oMask); } this.mask = null; } }, configKeyListeners: function (type, args, obj) { var listeners = args[0], listener, nListeners, i; if (listeners) { if (listeners instanceof Array) { nListeners = listeners.length; for (i = 0; i < nListeners; i++) { listener = listeners[i]; if (!Config.alreadySubscribed(this.showEvent, listener.enable, listener)) { this.showEvent.subscribe(listener.enable, listener, true); } if (!Config.alreadySubscribed(this.hideEvent, listener.disable, listener)) { this.hideEvent.subscribe(listener.disable, listener, true); this.destroyEvent.subscribe(listener.disable, listener, true); } } } else { if (!Config.alreadySubscribed(this.showEvent, listeners.enable, listeners)) { this.showEvent.subscribe(listeners.enable, listeners, true); } if (!Config.alreadySubscribed(this.hideEvent, listeners.disable, listeners)) { this.hideEvent.subscribe(listeners.disable, listeners, true); this.destroyEvent.subscribe(listeners.disable, listeners, true); } } } }, configHeight: function (type, args, obj) { var height = args[0], el = this.innerElement; Dom.setStyle(el, "height", height); this.cfg.refireEvent("iframe"); }, configWidth: function (type, args, obj) { var width = args[0], el = this.innerElement; Dom.setStyle(el, "width", width); this.cfg.refireEvent("iframe"); }, configzIndex: function (type, args, obj) { Panel.superclass.configzIndex.call(this, type, args, obj); if (this.mask || this.cfg.getProperty("modal") === true) { var panelZ = Dom.getStyle(this.element, "zIndex"); if (!panelZ || isNaN(panelZ)) { panelZ = 0; } if (panelZ === 0) { this.cfg.setProperty("zIndex", 1); } else { this.stackMask(); } } }, buildWrapper: function () { var elementParent = this.element.parentNode, originalElement = this.element, wrapper = document.createElement("div"); wrapper.className = Panel.CSS_PANEL_CONTAINER; wrapper.id = originalElement.id + "_c"; if (elementParent) { elementParent.insertBefore(wrapper, originalElement); } wrapper.appendChild(originalElement); this.element = wrapper; this.innerElement = originalElement; Dom.setStyle(this.innerElement, "visibility", "inherit"); }, sizeUnderlay: function () { var oUnderlay = this.underlay, oElement; if (oUnderlay) { oElement = this.element; oUnderlay.style.width = oElement.offsetWidth + "px"; oUnderlay.style.height = oElement.offsetHeight + "px"; } }, registerDragDrop: function () { var me = this; if (this.header) { if (!DD) { return; } this.dd = new DD(this.element.id, this.id); if (!this.header.id) { this.header.id = this.id + "_h"; } this.dd.startDrag = function () { var offsetHeight, offsetWidth, viewPortWidth, viewPortHeight, scrollX, scrollY, topConstraint, leftConstraint, bottomConstraint, rightConstraint; if (YAHOO.env.ua.ie == 6) { Dom.addClass(me.element, "drag"); } if (me.cfg.getProperty("constraintoviewport")) { offsetHeight = me.element.offsetHeight; offsetWidth = me.element.offsetWidth; viewPortWidth = Dom.getViewportWidth(); viewPortHeight = Dom.getViewportHeight(); scrollX = Dom.getDocumentScrollLeft(); scrollY = Dom.getDocumentScrollTop(); topConstraint = scrollY + 10; leftConstraint = scrollX + 10; bottomConstraint = scrollY + viewPortHeight - offsetHeight - 10; rightConstraint = scrollX + viewPortWidth - offsetWidth - 10; this.minX = leftConstraint; this.maxX = rightConstraint; this.constrainX = true; this.minY = topConstraint; this.maxY = bottomConstraint; this.constrainY = true; } else { this.constrainX = false; this.constrainY = false; } me.dragEvent.fire("startDrag", arguments); }; this.dd.onDrag = function () { me.syncPosition(); me.cfg.refireEvent("iframe"); if (this.platform == "mac" && YAHOO.env.ua.gecko) { this.showMacGeckoScrollbars(); } me.dragEvent.fire("onDrag", arguments); }; this.dd.endDrag = function () { if (YAHOO.env.ua.ie == 6) { Dom.removeClass(me.element, "drag"); } me.dragEvent.fire("endDrag", arguments); me.moveEvent.fire(me.cfg.getProperty("xy")); }; this.dd.setHandleElId(this.header.id); this.dd.addInvalidHandleType("INPUT"); this.dd.addInvalidHandleType("SELECT"); this.dd.addInvalidHandleType("TEXTAREA"); } }, buildMask: function () { var oMask = this.mask; if (!oMask) { if (!m_oMaskTemplate) { m_oMaskTemplate = document.createElement("div"); m_oMaskTemplate.className = "mask"; m_oMaskTemplate.innerHTML = "&#160;"; } oMask = m_oMaskTemplate.cloneNode(true); oMask.id = this.id + "_mask"; document.body.insertBefore(oMask, document.body.firstChild); this.mask = oMask; this.stackMask(); } }, hideMask: function () { if (this.cfg.getProperty("modal") && this.mask) { this.mask.style.display = "none"; this.hideMaskEvent.fire(); Dom.removeClass(document.body, "masked"); } }, showMask: function () { if (this.cfg.getProperty("modal") && this.mask) { Dom.addClass(document.body, "masked"); this.sizeMask(); this.mask.style.display = "block"; this.showMaskEvent.fire(); } }, sizeMask: function () { if (this.mask) { this.mask.style.height = Dom.getDocumentHeight() + "px"; this.mask.style.width = Dom.getDocumentWidth() + "px"; } }, stackMask: function () { if (this.mask) { var panelZ = Dom.getStyle(this.element, "zIndex"); if (!YAHOO.lang.isUndefined(panelZ) && !isNaN(panelZ)) { Dom.setStyle(this.mask, "zIndex", panelZ - 1); } } }, render: function (appendToNode) { return Panel.superclass.render.call(this, appendToNode, this.innerElement); }, destroy: function () { Overlay.windowResizeEvent.unsubscribe(this.sizeMask, this); this.removeMask(); if (this.close) { Event.purgeElement(this.close); } Panel.superclass.destroy.call(this); }, toString: function () { return "Panel " + this.id; } }); } ()); (function () { YAHOO.widget.Dialog = function (el, userConfig) { YAHOO.widget.Dialog.superclass.constructor.call(this, el, userConfig); }; var Event = YAHOO.util.Event, CustomEvent = YAHOO.util.CustomEvent, Dom = YAHOO.util.Dom, KeyListener = YAHOO.util.KeyListener, Connect = YAHOO.util.Connect, Dialog = YAHOO.widget.Dialog, Lang = YAHOO.lang, EVENT_TYPES = { "BEFORE_SUBMIT": "beforeSubmit", "SUBMIT": "submit", "MANUAL_SUBMIT": "manualSubmit", "ASYNC_SUBMIT": "asyncSubmit", "FORM_SUBMIT": "formSubmit", "CANCEL": "cancel" }, DEFAULT_CONFIG = { "POST_METHOD": { key: "postmethod", value: "async" }, "BUTTONS": { key: "buttons", value: "none"} }; Dialog.CSS_DIALOG = "yui-dialog"; function removeButtonEventHandlers() { var aButtons = this._aButtons, nButtons, oButton, i; if (Lang.isArray(aButtons)) { nButtons = aButtons.length; if (nButtons > 0) { i = nButtons - 1; do { oButton = aButtons[i]; if (YAHOO.widget.Button && oButton instanceof YAHOO.widget.Button) { oButton.destroy(); } else { if (oButton.tagName.toUpperCase() == "BUTTON") { Event.purgeElement(oButton); Event.purgeElement(oButton, false); } } } while (i--); } } } YAHOO.extend(Dialog, YAHOO.widget.Panel, { form: null, initDefaultConfig: function () { Dialog.superclass.initDefaultConfig.call(this); this.callback = { success: null, failure: null, argument: null }; this.cfg.addProperty(DEFAULT_CONFIG.POST_METHOD.key, { handler: this.configPostMethod, value: DEFAULT_CONFIG.POST_METHOD.value, validator: function (val) { if (val != "form" && val != "async" && val != "none" && val != "manual") { return false; } else { return true; } } }); this.cfg.addProperty(DEFAULT_CONFIG.BUTTONS.key, { handler: this.configButtons, value: DEFAULT_CONFIG.BUTTONS.value }); }, initEvents: function () { Dialog.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; this.beforeSubmitEvent = this.createEvent(EVENT_TYPES.BEFORE_SUBMIT); this.beforeSubmitEvent.signature = SIGNATURE; this.submitEvent = this.createEvent(EVENT_TYPES.SUBMIT); this.submitEvent.signature = SIGNATURE; this.manualSubmitEvent = this.createEvent(EVENT_TYPES.MANUAL_SUBMIT); this.manualSubmitEvent.signature = SIGNATURE; this.asyncSubmitEvent = this.createEvent(EVENT_TYPES.ASYNC_SUBMIT); this.asyncSubmitEvent.signature = SIGNATURE; this.formSubmitEvent = this.createEvent(EVENT_TYPES.FORM_SUBMIT); this.formSubmitEvent.signature = SIGNATURE; this.cancelEvent = this.createEvent(EVENT_TYPES.CANCEL); this.cancelEvent.signature = SIGNATURE; }, init: function (el, userConfig) { Dialog.superclass.init.call(this, el); this.beforeInitEvent.fire(Dialog); Dom.addClass(this.element, Dialog.CSS_DIALOG); this.cfg.setProperty("visible", false); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.showEvent.subscribe(this.focusFirst, this, true); this.beforeHideEvent.subscribe(this.blurButtons, this, true); this.subscribe("changeBody", this.registerForm); this.initEvent.fire(Dialog); }, doSubmit: function () { var oForm = this.form, bUseFileUpload = false, bUseSecureFileUpload = false, aElements, nElements, i, sMethod; switch (this.cfg.getProperty("postmethod")) { case "async": aElements = oForm.elements; nElements = aElements.length; if (nElements > 0) { i = nElements - 1; do { if (aElements[i].type == "file") { bUseFileUpload = true; break; } } while (i--); } if (bUseFileUpload && YAHOO.env.ua.ie && this.isSecure) { bUseSecureFileUpload = true; } sMethod = (oForm.getAttribute("method") || "POST").toUpperCase(); Connect.setForm(oForm, bUseFileUpload, bUseSecureFileUpload); Connect.asyncRequest(sMethod, oForm.getAttribute("action"), this.callback); this.asyncSubmitEvent.fire(); break; case "form": oForm.submit(); this.formSubmitEvent.fire(); break; case "none": case "manual": this.manualSubmitEvent.fire(); break; } }, registerForm: function () { var form = this.element.getElementsByTagName("form")[0], me = this, firstElement, lastElement; if (this.form) { if (this.form == form && Dom.isAncestor(this.element, this.form)) { return; } else { Event.purgeElement(this.form); this.form = null; } } if (!form) { form = document.createElement("form"); form.name = "frm_" + this.id; this.body.appendChild(form); } if (form) { this.form = form; Event.on(form, "submit", function (e) { Event.stopEvent(e); this.submit(); this.form.blur(); }, this, true); this.firstFormElement = function () { var f, el, nElements = form.elements.length; for (f = 0; f < nElements; f++) { el = form.elements[f]; if (el.focus && !el.disabled && el.type != "hidden") { return el; } } return null; } (); this.lastFormElement = function () { var f, el, nElements = form.elements.length; for (f = nElements - 1; f >= 0; f--) { el = form.elements[f]; if (el.focus && !el.disabled && el.type != "hidden") { return el; } } return null; } (); if (this.cfg.getProperty("modal")) { firstElement = this.firstFormElement || this.firstButton; if (firstElement) { this.preventBackTab = new KeyListener(firstElement, { shift: true, keys: 9 }, { fn: me.focusLast, scope: me, correctScope: true }); this.showEvent.subscribe(this.preventBackTab.enable, this.preventBackTab, true); this.hideEvent.subscribe(this.preventBackTab.disable, this.preventBackTab, true); } lastElement = this.lastButton || this.lastFormElement; if (lastElement) { this.preventTabOut = new KeyListener(lastElement, { shift: false, keys: 9 }, { fn: me.focusFirst, scope: me, correctScope: true }); this.showEvent.subscribe(this.preventTabOut.enable, this.preventTabOut, true); this.hideEvent.subscribe(this.preventTabOut.disable, this.preventTabOut, true); } } } }, configClose: function (type, args, obj) { var val = args[0]; function doCancel(e, obj) { obj.cancel(); } if (val) { if (!this.close) { this.close = document.createElement("div"); Dom.addClass(this.close, "container-close"); this.close.innerHTML = "&#160;"; this.innerElement.appendChild(this.close); Event.on(this.close, "click", doCancel, this); } else { this.close.style.display = "block"; } } else { if (this.close) { this.close.style.display = "none"; } } }, configButtons: function (type, args, obj) { var Button = YAHOO.widget.Button, aButtons = args[0], oInnerElement = this.innerElement, oButton, oButtonEl, oYUIButton, nButtons, oSpan, oFooter, i; removeButtonEventHandlers.call(this); this._aButtons = null; if (Lang.isArray(aButtons)) { oSpan = document.createElement("span"); oSpan.className = "button-group"; nButtons = aButtons.length; this._aButtons = []; for (i = 0; i < nButtons; i++) { oButton = aButtons[i]; if (Button) { oYUIButton = new Button({ label: oButton.text, container: oSpan }); oButtonEl = oYUIButton.get("element"); if (oButton.isDefault) { oYUIButton.addClass("default"); this.defaultHtmlButton = oButtonEl; } if (Lang.isFunction(oButton.handler)) { oYUIButton.set("onclick", { fn: oButton.handler, obj: this, scope: this }); } else { if (Lang.isObject(oButton.handler) && Lang.isFunction(oButton.handler.fn)) { oYUIButton.set("onclick", { fn: oButton.handler.fn, obj: ((!Lang.isUndefined(oButton.handler.obj)) ? oButton.handler.obj : this), scope: (oButton.handler.scope || this) }); } } this._aButtons[this._aButtons.length] = oYUIButton; } else { oButtonEl = document.createElement("button"); oButtonEl.setAttribute("type", "button"); if (oButton.isDefault) { oButtonEl.className = "default"; this.defaultHtmlButton = oButtonEl; } oButtonEl.innerHTML = oButton.text; if (Lang.isFunction(oButton.handler)) { Event.on(oButtonEl, "click", oButton.handler, this, true); } else { if (Lang.isObject(oButton.handler) && Lang.isFunction(oButton.handler.fn)) { Event.on(oButtonEl, "click", oButton.handler.fn, ((!Lang.isUndefined(oButton.handler.obj)) ? oButton.handler.obj : this), (oButton.handler.scope || this)); } } oSpan.appendChild(oButtonEl); this._aButtons[this._aButtons.length] = oButtonEl; } oButton.htmlButton = oButtonEl; if (i === 0) { this.firstButton = oButtonEl; } if (i == (nButtons - 1)) { this.lastButton = oButtonEl; } } this.setFooter(oSpan); oFooter = this.footer; if (Dom.inDocument(this.element) && !Dom.isAncestor(oInnerElement, oFooter)) { oInnerElement.appendChild(oFooter); } this.buttonSpan = oSpan; } else { oSpan = this.buttonSpan; oFooter = this.footer; if (oSpan && oFooter) { oFooter.removeChild(oSpan); this.buttonSpan = null; this.firstButton = null; this.lastButton = null; this.defaultHtmlButton = null; } } this.cfg.refireEvent("iframe"); this.cfg.refireEvent("underlay"); }, getButtons: function () { var aButtons = this._aButtons; if (aButtons) { return aButtons; } }, focusFirst: function (type, args, obj) { var oElement = this.firstFormElement, oEvent; if (args) { oEvent = args[1]; if (oEvent) { Event.stopEvent(oEvent); } } if (oElement) { try { oElement.focus(); } catch (oException) { } } else { this.focusDefaultButton(); } }, focusLast: function (type, args, obj) { var aButtons = this.cfg.getProperty("buttons"), oElement = this.lastFormElement, oEvent; if (args) { oEvent = args[1]; if (oEvent) { Event.stopEvent(oEvent); } } if (aButtons && Lang.isArray(aButtons)) { this.focusLastButton(); } else { if (oElement) { try { oElement.focus(); } catch (oException) { } } } }, focusDefaultButton: function () { var oElement = this.defaultHtmlButton; if (oElement) { try { oElement.focus(); } catch (oException) { } } }, blurButtons: function () { var aButtons = this.cfg.getProperty("buttons"), nButtons, oButton, oElement, i; if (aButtons && Lang.isArray(aButtons)) { nButtons = aButtons.length; if (nButtons > 0) { i = (nButtons - 1); do { oButton = aButtons[i]; if (oButton) { oElement = oButton.htmlButton; if (oElement) { try { oElement.blur(); } catch (oException) { } } } } while (i--); } } }, focusFirstButton: function () { var aButtons = this.cfg.getProperty("buttons"), oButton, oElement; if (aButtons && Lang.isArray(aButtons)) { oButton = aButtons[0]; if (oButton) { oElement = oButton.htmlButton; if (oElement) { try { oElement.focus(); } catch (oException) { } } } } }, focusLastButton: function () { var aButtons = this.cfg.getProperty("buttons"), nButtons, oButton, oElement; if (aButtons && Lang.isArray(aButtons)) { nButtons = aButtons.length; if (nButtons > 0) { oButton = aButtons[(nButtons - 1)]; if (oButton) { oElement = oButton.htmlButton; if (oElement) { try { oElement.focus(); } catch (oException) { } } } } } }, configPostMethod: function (type, args, obj) { var postmethod = args[0]; this.registerForm(); }, validate: function () { return true; }, submit: function () { if (this.validate()) { this.beforeSubmitEvent.fire(); this.doSubmit(); this.submitEvent.fire(); this.hide(); return true; } else { return false; } }, cancel: function () { this.cancelEvent.fire(); this.hide(); }, getData: function () { var oForm = this.form, aElements, nTotalElements, oData, sName, oElement, nElements, sType, sTagName, aOptions, nOptions, aValues, oOption, sValue, oRadio, oCheckbox, i, n; function isFormElement(p_oElement) { var sTag = p_oElement.tagName.toUpperCase(); return ((sTag == "INPUT" || sTag == "TEXTAREA" || sTag == "SELECT") && p_oElement.name == sName); } if (oForm) { aElements = oForm.elements; nTotalElements = aElements.length; oData = {}; for (i = 0; i < nTotalElements; i++) { sName = aElements[i].name; oElement = Dom.getElementsBy(isFormElement, "*", oForm); nElements = oElement.length; if (nElements > 0) { if (nElements == 1) { oElement = oElement[0]; sType = oElement.type; sTagName = oElement.tagName.toUpperCase(); switch (sTagName) { case "INPUT": if (sType == "checkbox") { oData[sName] = oElement.checked; } else { if (sType != "radio") { oData[sName] = oElement.value; } } break; case "TEXTAREA": oData[sName] = oElement.value; break; case "SELECT": aOptions = oElement.options; nOptions = aOptions.length; aValues = []; for (n = 0; n < nOptions; n++) { oOption = aOptions[n]; if (oOption.selected) { sValue = oOption.value; if (!sValue || sValue === "") { sValue = oOption.text; } aValues[aValues.length] = sValue; } } oData[sName] = aValues; break; } } else { sType = oElement[0].type; switch (sType) { case "radio": for (n = 0; n < nElements; n++) { oRadio = oElement[n]; if (oRadio.checked) { oData[sName] = oRadio.value; break; } } break; case "checkbox": aValues = []; for (n = 0; n < nElements; n++) { oCheckbox = oElement[n]; if (oCheckbox.checked) { aValues[aValues.length] = oCheckbox.value; } } oData[sName] = aValues; break; } } } } } return oData; }, destroy: function () { removeButtonEventHandlers.call(this); this._aButtons = null; var aForms = this.element.getElementsByTagName("form"), oForm; if (aForms.length > 0) { oForm = aForms[0]; if (oForm) { Event.purgeElement(oForm); if (oForm.parentNode) { oForm.parentNode.removeChild(oForm); } this.form = null; } } Dialog.superclass.destroy.call(this); }, toString: function () { return "Dialog " + this.id; } }); } ()); (function () { YAHOO.widget.SimpleDialog = function (el, userConfig) { YAHOO.widget.SimpleDialog.superclass.constructor.call(this, el, userConfig); }; var Dom = YAHOO.util.Dom, SimpleDialog = YAHOO.widget.SimpleDialog, DEFAULT_CONFIG = { "ICON": { key: "icon", value: "none", suppressEvent: true }, "TEXT": { key: "text", value: "", suppressEvent: true, supercedes: ["icon"]} }; SimpleDialog.ICON_BLOCK = "blckicon"; SimpleDialog.ICON_ALARM = "alrticon"; SimpleDialog.ICON_HELP = "hlpicon"; SimpleDialog.ICON_INFO = "infoicon"; SimpleDialog.ICON_WARN = "warnicon"; SimpleDialog.ICON_TIP = "tipicon"; SimpleDialog.ICON_CSS_CLASSNAME = "yui-icon"; SimpleDialog.CSS_SIMPLEDIALOG = "yui-simple-dialog"; YAHOO.extend(SimpleDialog, YAHOO.widget.Dialog, { initDefaultConfig: function () { SimpleDialog.superclass.initDefaultConfig.call(this); this.cfg.addProperty(DEFAULT_CONFIG.ICON.key, { handler: this.configIcon, value: DEFAULT_CONFIG.ICON.value, suppressEvent: DEFAULT_CONFIG.ICON.suppressEvent }); this.cfg.addProperty(DEFAULT_CONFIG.TEXT.key, { handler: this.configText, value: DEFAULT_CONFIG.TEXT.value, suppressEvent: DEFAULT_CONFIG.TEXT.suppressEvent, supercedes: DEFAULT_CONFIG.TEXT.supercedes }); }, init: function (el, userConfig) { SimpleDialog.superclass.init.call(this, el); this.beforeInitEvent.fire(SimpleDialog); Dom.addClass(this.element, SimpleDialog.CSS_SIMPLEDIALOG); this.cfg.queueProperty("postmethod", "manual"); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.beforeRenderEvent.subscribe(function () { if (!this.body) { this.setBody(""); } }, this, true); this.initEvent.fire(SimpleDialog); }, registerForm: function () { SimpleDialog.superclass.registerForm.call(this); this.form.innerHTML += '<input type="hidden" name="' + this.id + '" value=""/>'; }, configIcon: function (type, args, obj) { var sIcon = args[0], oBody = this.body, sCSSClass = SimpleDialog.ICON_CSS_CLASSNAME, oIcon, oIconParent; if (sIcon && sIcon != "none") { oIcon = Dom.getElementsByClassName(sCSSClass, "*", oBody); if (oIcon) { oIconParent = oIcon.parentNode; if (oIconParent) { oIconParent.removeChild(oIcon); oIcon = null; } } if (sIcon.indexOf(".") == -1) { oIcon = document.createElement("span"); oIcon.className = (sCSSClass + " " + sIcon); oIcon.innerHTML = "&#160;"; } else { oIcon = document.createElement("img"); oIcon.src = (this.imageRoot + sIcon); oIcon.className = sCSSClass; } if (oIcon) { oBody.insertBefore(oIcon, oBody.firstChild); } } }, configText: function (type, args, obj) { var text = args[0]; if (text) { this.setBody(text); this.cfg.refireEvent("icon"); } }, toString: function () { return "SimpleDialog " + this.id; } }); } ()); (function () { YAHOO.widget.ContainerEffect = function (overlay, attrIn, attrOut, targetElement, animClass) { if (!animClass) { animClass = YAHOO.util.Anim; } this.overlay = overlay; this.attrIn = attrIn; this.attrOut = attrOut; this.targetElement = targetElement || overlay.element; this.animClass = animClass; }; var Dom = YAHOO.util.Dom, CustomEvent = YAHOO.util.CustomEvent, Easing = YAHOO.util.Easing, ContainerEffect = YAHOO.widget.ContainerEffect; ContainerEffect.FADE = function (overlay, dur) { var fade = new ContainerEffect(overlay, { attributes: { opacity: { from: 0, to: 1} }, duration: dur, method: Easing.easeIn }, { attributes: { opacity: { to: 0} }, duration: dur, method: Easing.easeOut }, overlay.element); fade.handleStartAnimateIn = function (type, args, obj) { Dom.addClass(obj.overlay.element, "hide-select"); if (!obj.overlay.underlay) { obj.overlay.cfg.refireEvent("underlay"); } if (obj.overlay.underlay) { obj.initialUnderlayOpacity = Dom.getStyle(obj.overlay.underlay, "opacity"); obj.overlay.underlay.style.filter = null; } Dom.setStyle(obj.overlay.element, "visibility", "visible"); Dom.setStyle(obj.overlay.element, "opacity", 0); }; fade.handleCompleteAnimateIn = function (type, args, obj) { Dom.removeClass(obj.overlay.element, "hide-select"); if (obj.overlay.element.style.filter) { obj.overlay.element.style.filter = null; } if (obj.overlay.underlay) { Dom.setStyle(obj.overlay.underlay, "opacity", obj.initialUnderlayOpacity); } obj.overlay.cfg.refireEvent("iframe"); obj.animateInCompleteEvent.fire(); }; fade.handleStartAnimateOut = function (type, args, obj) { Dom.addClass(obj.overlay.element, "hide-select"); if (obj.overlay.underlay) { obj.overlay.underlay.style.filter = null; } }; fade.handleCompleteAnimateOut = function (type, args, obj) { Dom.removeClass(obj.overlay.element, "hide-select"); if (obj.overlay.element.style.filter) { obj.overlay.element.style.filter = null; } Dom.setStyle(obj.overlay.element, "visibility", "hidden"); Dom.setStyle(obj.overlay.element, "opacity", 1); obj.overlay.cfg.refireEvent("iframe"); obj.animateOutCompleteEvent.fire(); }; fade.init(); return fade; }; ContainerEffect.SLIDE = function (overlay, dur) { var x = overlay.cfg.getProperty("x") || Dom.getX(overlay.element), y = overlay.cfg.getProperty("y") || Dom.getY(overlay.element), clientWidth = Dom.getClientWidth(), offsetWidth = overlay.element.offsetWidth, slide = new ContainerEffect(overlay, { attributes: { points: { to: [x, y]} }, duration: dur, method: Easing.easeIn }, { attributes: { points: { to: [(clientWidth + 25), y]} }, duration: dur, method: Easing.easeOut }, overlay.element, YAHOO.util.Motion); slide.handleStartAnimateIn = function (type, args, obj) { obj.overlay.element.style.left = ((-25) - offsetWidth) + "px"; obj.overlay.element.style.top = y + "px"; }; slide.handleTweenAnimateIn = function (type, args, obj) { var pos = Dom.getXY(obj.overlay.element), currentX = pos[0], currentY = pos[1]; if (Dom.getStyle(obj.overlay.element, "visibility") == "hidden" && currentX < x) { Dom.setStyle(obj.overlay.element, "visibility", "visible"); } obj.overlay.cfg.setProperty("xy", [currentX, currentY], true); obj.overlay.cfg.refireEvent("iframe"); }; slide.handleCompleteAnimateIn = function (type, args, obj) { obj.overlay.cfg.setProperty("xy", [x, y], true); obj.startX = x; obj.startY = y; obj.overlay.cfg.refireEvent("iframe"); obj.animateInCompleteEvent.fire(); }; slide.handleStartAnimateOut = function (type, args, obj) { var vw = Dom.getViewportWidth(), pos = Dom.getXY(obj.overlay.element), yso = pos[1], currentTo = obj.animOut.attributes.points.to; obj.animOut.attributes.points.to = [(vw + 25), yso]; }; slide.handleTweenAnimateOut = function (type, args, obj) { var pos = Dom.getXY(obj.overlay.element), xto = pos[0], yto = pos[1]; obj.overlay.cfg.setProperty("xy", [xto, yto], true); obj.overlay.cfg.refireEvent("iframe"); }; slide.handleCompleteAnimateOut = function (type, args, obj) { Dom.setStyle(obj.overlay.element, "visibility", "hidden"); obj.overlay.cfg.setProperty("xy", [x, y]); obj.animateOutCompleteEvent.fire(); }; slide.init(); return slide; }; ContainerEffect.prototype = { init: function () { this.beforeAnimateInEvent = this.createEvent("beforeAnimateIn"); this.beforeAnimateInEvent.signature = CustomEvent.LIST; this.beforeAnimateOutEvent = this.createEvent("beforeAnimateOut"); this.beforeAnimateOutEvent.signature = CustomEvent.LIST; this.animateInCompleteEvent = this.createEvent("animateInComplete"); this.animateInCompleteEvent.signature = CustomEvent.LIST; this.animateOutCompleteEvent = this.createEvent("animateOutComplete"); this.animateOutCompleteEvent.signature = CustomEvent.LIST; this.animIn = new this.animClass(this.targetElement, this.attrIn.attributes, this.attrIn.duration, this.attrIn.method); this.animIn.onStart.subscribe(this.handleStartAnimateIn, this); this.animIn.onTween.subscribe(this.handleTweenAnimateIn, this); this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn, this); this.animOut = new this.animClass(this.targetElement, this.attrOut.attributes, this.attrOut.duration, this.attrOut.method); this.animOut.onStart.subscribe(this.handleStartAnimateOut, this); this.animOut.onTween.subscribe(this.handleTweenAnimateOut, this); this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut, this); }, animateIn: function () { this.beforeAnimateInEvent.fire(); this.animIn.animate(); }, animateOut: function () { this.beforeAnimateOutEvent.fire(); this.animOut.animate(); }, handleStartAnimateIn: function (type, args, obj) { }, handleTweenAnimateIn: function (type, args, obj) { }, handleCompleteAnimateIn: function (type, args, obj) { }, handleStartAnimateOut: function (type, args, obj) { }, handleTweenAnimateOut: function (type, args, obj) { }, handleCompleteAnimateOut: function (type, args, obj) { }, toString: function () { var output = "ContainerEffect"; if (this.overlay) { output += " [" + this.overlay.toString() + "]"; } return output; } }; YAHOO.lang.augmentProto(ContainerEffect, YAHOO.util.EventProvider); })(); YAHOO.register("container", YAHOO.widget.Module, { version: "2.3.1", build: "541" });


/******************************************************************************
Name:    Highslide JS
Version: 3.3.12 (Feb 29 2008)
Config:  default
Author:  Torstein Hønsi
Support: http://vikjavev.no/highslide/forum

Licence:
Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5
License (http://creativecommons.org/licenses/by-nc/2.5/).

You are free:
* to copy, distribute, display, and perform the work
* to make derivative works

Under the following conditions:
* Attribution. You must attribute the work in the manner  specified by  the
author or licensor.
* Noncommercial. You may not use this work for commercial purposes.

* For  any  reuse  or  distribution, you  must make clear to others the license
terms of this work.
* Any  of  these  conditions  can  be  waived  if  you  get permission from the 
copyright holder.

Your fair use and other rights are in no way affected by the above.
******************************************************************************/
// Highslide: /scripts/highslide.js
var hs = { graphicsDir: "highslide/graphics/", restoreCursor: "zoomout.cur", expandSteps: 10, expandDuration: 150, restoreSteps: 10, restoreDuration: 150, marginLeft: 15, marginRight: 15, marginTop: 15, marginBottom: 15, zIndexCounter: 1001, restoreTitle: "Click to close image, click and drag to move. Use arrow keys for next and previous.", loadingText: "Loading...", loadingTitle: "Click to cancel", loadingOpacity: 0.75, focusTitle: "Click to bring to front", allowMultipleInstances: true, numberOfImagesToPreload: 5, captionSlideSpeed: 1, padToMinWidth: false, outlineWhileAnimating: 2, outlineStartOffset: 3, fullExpandTitle: "Expand to actual size", fullExpandPosition: "bottom right", fullExpandOpacity: 1, showCredits: false, creditsText: "Powered by <i>Highslide JS</i>", creditsHref: "http://vikjavev.no/highslide/", creditsTitle: "Go to the Highslide JS homepage", enableKeyListener: true, captionId: null, spaceForCaption: 30, slideshowGroup: null, minWidth: 200, minHeight: 200, allowSizeReduction: true, outlineType: "drop-shadow", wrapperClassName: "highslide-wrapper", preloadTheseImages: [], continuePreloading: true, expanders: [], overrides: ["allowSizeReduction", "outlineType", "outlineWhileAnimating", "spaceForCaption", "captionId", "captionText", "captionEval", "wrapperClassName", "minWidth", "minHeight", "slideshowGroup", "easing", "easingClose", "fadeInOut"], overlays: [], faders: [], pendingOutlines: {}, clones: {}, ie: (document.all && !window.opera), safari: /Safari/.test(navigator.userAgent), geckoMac: /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent), $: function (id) { return document.getElementById(id); }, push: function (arr, val) { arr[arr.length] = val; }, createElement: function (tag, attribs, styles, parent, nopad) { var el = document.createElement(tag); if (attribs) { hs.setAttribs(el, attribs); } if (nopad) { hs.setStyles(el, { padding: 0, border: "none", margin: 0 }); } if (styles) { hs.setStyles(el, styles); } if (parent) { parent.appendChild(el); } return el; }, setAttribs: function (el, attribs) { for (var x in attribs) { el[x] = attribs[x]; } }, setStyles: function (el, styles) { for (var x in styles) { try { if (hs.ie && x == "opacity") { el.style.filter = (styles[x] == 1) ? "" : "alpha(opacity=" + (styles[x] * 100) + ")"; } else { el.style[x] = styles[x]; } } catch (e) { } } }, ieVersion: function () { var arr = navigator.appVersion.split("MSIE"); return arr[1] ? parseFloat(arr[1]) : null; }, getPageSize: function () { var iebody = document.compatMode && document.compatMode != "BackCompat" ? document.documentElement : document.body; var width = hs.ie ? iebody.clientWidth : (document.documentElement.clientWidth || self.innerWidth), height = hs.ie ? iebody.clientHeight : self.innerHeight; return { width: width, height: height, scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset, scrollTop: hs.ie ? iebody.scrollTop : pageYOffset }; }, position: function (el) { var p = { x: el.offsetLeft, y: el.offsetTop }; while (el.offsetParent) { el = el.offsetParent; p.x += el.offsetLeft; p.y += el.offsetTop; if (el != document.body && el != document.documentElement) { p.x -= el.scrollLeft; p.y -= el.scrollTop; } } return p; }, expand: function (a, params, custom) { if (a.getParams) { return params; } try { new hs.Expander(a, params, custom); return false; } catch (e) { return true; } }, focusTopmost: function () { var topZ = 0, topmostKey = -1; for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i]) { if (hs.expanders[i].wrapper.style.zIndex && hs.expanders[i].wrapper.style.zIndex > topZ) { topZ = hs.expanders[i].wrapper.style.zIndex; topmostKey = i; } } } if (topmostKey == -1) { hs.focusKey = -1; } else { hs.expanders[topmostKey].focus(); } }, getAdjacentAnchor: function (key, op) { var aAr = document.getElementsByTagName("A"), hsAr = {}, activeI = -1, j = 0; for (var i = 0; i < aAr.length; i++) { if (hs.isHsAnchor(aAr[i]) && ((hs.expanders[key].slideshowGroup == hs.getParam(aAr[i], "slideshowGroup")))) { hsAr[j] = aAr[i]; if (hs.expanders[key] && aAr[i] == hs.expanders[key].a) { activeI = j; } j++; } } return hsAr[activeI + op] || null; }, getParam: function (a, param) { a.getParams = a.onclick; var p = a.getParams ? a.getParams() : null; a.getParams = null; return (p && typeof p[param] != "undefined") ? p[param] : (typeof hs[param] != "undefined" ? hs[param] : null); }, getSrc: function (a) { var src = hs.getParam(a, "src"); if (src) { return src; } return a.href; }, getNode: function (id) { var node = hs.$(id), clone = hs.clones[id], a = {}; if (!node && !clone) { return null; } if (!clone) { clone = node.cloneNode(true); clone.id = ""; hs.clones[id] = clone; return node; } else { return clone.cloneNode(true); } }, purge: function (d) { if (!hs.ie) { return; } var a = d.attributes, i, l, n; if (a) { l = a.length; for (var i = 0; i < l; i += 1) { n = a[i].name; if (typeof d[n] === "function") { d[n] = null; } } } a = d.childNodes; if (a) { l = a.length; for (var i = 0; i < l; i += 1) { hs.purge(d.childNodes[i]); } } }, previousOrNext: function (el, op) { var exp = hs.last = hs.getExpander(el); try { var adj = hs.upcoming = hs.getAdjacentAnchor(exp.key, op); adj.onclick(); } catch (e) { } try { exp.close(); } catch (e) { } return false; }, previous: function (el) { return hs.previousOrNext(el, -1); }, next: function (el) { return hs.previousOrNext(el, 1); }, keyHandler: function (e) { if (!e) { e = window.event; } if (!e.target) { e.target = e.srcElement; } if (e.target.form) { return true; } var op = null; switch (e.keyCode) { case 32: case 34: case 39: case 40: op = 1; break; case 8: case 33: case 37: case 38: op = -1; break; case 27: case 13: op = 0; } if (op !== null) { hs.removeEventListener(document, "keydown", hs.keyHandler); if (!hs.enableKeyListener) { return true; } if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } if (op == 0) { try { hs.getExpander().close(); } catch (e) { } return false; } else { return hs.previousOrNext(hs.focusKey, op); } } return true; }, registerOverlay: function (overlay) { hs.push(hs.overlays, overlay); }, getWrapperKey: function (element) { var el, re = /^highslide-wrapper-([0-9]+)$/; el = element; while (el.parentNode) { if (el.id && re.test(el.id)) { return el.id.replace(re, "$1"); } el = el.parentNode; } el = element; while (el.parentNode) { if (el.tagName && hs.isHsAnchor(el)) { for (var key = 0; key < hs.expanders.length; key++) { var exp = hs.expanders[key]; if (exp && exp.a == el) { return key; } } } el = el.parentNode; } return null; }, getExpander: function (el) { if (typeof el == "undefined") { return hs.expanders[hs.focusKey] || null; } if (typeof el == "number") { return hs.expanders[el] || null; } if (typeof el == "string") { el = hs.$(el); } return hs.expanders[hs.getWrapperKey(el)] || null; }, isHsAnchor: function (a) { return (a.onclick && a.onclick.toString().replace(/\s/g, " ").match(/hs.(htmlE|e)xpand/)); }, cleanUp: function () { for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].isExpanded) { hs.focusTopmost(); } } }, mouseClickHandler: function (e) { if (!e) { e = window.event; } if (e.button > 1) { return true; } if (!e.target) { e.target = e.srcElement; } var el = e.target; while (el.parentNode && !(/highslide-(image|move|html|resize)/.test(el.className))) { el = el.parentNode; } var exp = hs.getExpander(el); if (exp && (exp.isClosing || !exp.isExpanded)) { return true; } if (exp && e.type == "mousedown") { if (e.target.form) { return true; } var match = el.className.match(/highslide-(image|move|resize)/); if (match) { hs.dragArgs = { exp: exp, type: match[1], left: exp.x.min, width: exp.x.span, top: exp.y.min, height: exp.y.span, clickX: e.clientX, clickY: e.clientY }; hs.addEventListener(document, "mousemove", hs.dragHandler); if (e.preventDefault) { e.preventDefault(); } if (/highslide-(image|html)-blur/.test(exp.content.className)) { exp.focus(); hs.hasFocused = true; } return false; } } else { if (e.type == "mouseup") { hs.removeEventListener(document, "mousemove", hs.dragHandler); if (hs.dragArgs) { if (hs.dragArgs.type == "image") { hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor; } var hasDragged = hs.dragArgs.hasDragged; if (!hasDragged && !hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) { exp.close(); } else { if (hasDragged || (!hasDragged && hs.hasHtmlexpanders)) { hs.dragArgs.exp.redoShowHide(); } } hs.hasFocused = false; hs.dragArgs = null; } else { if (/highslide-image-blur/.test(el.className)) { el.style.cursor = hs.styleRestoreCursor; } } } } return false; }, dragHandler: function (e) { if (!hs.dragArgs) { return true; } if (!e) { e = window.event; } var a = hs.dragArgs, exp = a.exp; a.dX = e.clientX - a.clickX; a.dY = e.clientY - a.clickY; var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2)); a.hasDragged = (a.type != "image" && distance > 0) || (distance > (hs.dragSensitivity || 5)); if (a.hasDragged) { exp.move(a); } return false; }, addEventListener: function (el, event, func) { try { el.addEventListener(event, func, false); } catch (e) { try { el.detachEvent("on" + event, func); el.attachEvent("on" + event, func); } catch (e) { el["on" + event] = func; } } }, removeEventListener: function (el, event, func) { try { el.removeEventListener(event, func, false); } catch (e) { try { el.detachEvent("on" + event, func); } catch (e) { el["on" + event] = null; } } }, preloadFullImage: function (i) { if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != "undefined") { var img = document.createElement("img"); img.onload = function () { hs.preloadFullImage(i + 1); }; img.src = hs.preloadTheseImages[i]; } }, preloadImages: function (number) { if (number && typeof number != "object") { hs.numberOfImagesToPreload = number; } var a, re, j = 0; var aTags = document.getElementsByTagName("A"); for (var i = 0; i < aTags.length; i++) { a = aTags[i]; re = hs.isHsAnchor(a); if (re && re[0] == "hs.expand") { if (j < hs.numberOfImagesToPreload) { hs.preloadTheseImages[j] = hs.getSrc(a); j++; } } } new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0); }); var cur = hs.createElement("img", { src: hs.graphicsDir + hs.restoreCursor }); }, genContainer: function () { if (!hs.container) { hs.container = hs.createElement("div", null, { position: "absolute", left: 0, top: 0, width: "100%", zIndex: hs.zIndexCounter }, document.body, true); hs.loading = hs.createElement("a", { className: "highslide-loading", title: hs.loadingTitle, innerHTML: hs.loadingText, href: "javascript:void(0)" }, { position: "absolute", opacity: hs.loadingOpacity, left: "-9999px", zIndex: 1 }, hs.container); Math.linearTween = function (t, b, c, d) { return c * t / d + b; }; Math.easeInQuad = function (t, b, c, d) { return c * (t /= d) * t + b; }; } }, fade: function (el, o, oFinal, dur, i, dir) { if (typeof i == "undefined") { if (typeof dur != "number") { dur = 250; } if (dur < 25) { hs.setStyles(el, { opacity: oFinal, visibility: (o < oFinal ? "visible" : "hidden") }); return; } i = hs.faders.length; dir = oFinal > o ? 1 : -1; var step = (25 / (dur - dur % 25)) * Math.abs(o - oFinal); } o = parseFloat(o); el.style.visibility = (o <= 0) ? "hidden" : "visible"; if (o < 0 || (dir == 1 && o > oFinal)) { return; } if (el.fading && el.fading.i != i) { clearTimeout(hs.faders[el.fading.i]); o = el.fading.o; } el.fading = { i: i, o: o, step: (step || el.fading.step) }; el.style.visibility = (o <= 0) ? "hidden" : "visible"; hs.setStyles(el, { opacity: o }); hs.faders[i] = setTimeout(function () { hs.fade(el, o + el.fading.step * dir, oFinal, null, i, dir); }, 25); }, close: function (el) { try { hs.getExpander(el).close(); } catch (e) { } return false; } }; hs.Outline = function (outlineType, onLoad) { this.onLoad = onLoad; this.outlineType = outlineType; var v = hs.ieVersion(), tr; this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7; if (!outlineType) { if (onLoad) { onLoad(); } return; } hs.genContainer(); this.table = hs.createElement("table", { cellSpacing: 0 }, { visibility: "hidden", position: "absolute", borderCollapse: "collapse", backgroundColor: "transparent" }, hs.container, true); this.tbody = hs.createElement("tbody", null, null, this.table, 1); this.td = []; for (var i = 0; i <= 8; i++) { if (i % 3 == 0) { tr = hs.createElement("tr", null, { height: "auto" }, this.tbody, true); } this.td[i] = hs.createElement("td", null, null, tr, true); var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position: "relative" }; hs.setStyles(this.td[i], style); } this.td[4].className = outlineType; this.preloadGraphic(); }; hs.Outline.prototype = { preloadGraphic: function () { var src = hs.graphicsDir + (hs.outlinesDir || "outlines/") + this.outlineType + ".png"; var appendTo = hs.safari ? hs.container : null; this.graphic = hs.createElement("img", null, { position: "absolute", left: "-9999px", top: "-9999px" }, appendTo, true); var pThis = this; this.graphic.onload = function () { pThis.onGraphicLoad(); }; this.graphic.src = src; }, onGraphicLoad: function () { var o = this.offset = this.graphic.width / 4, pos = [[0, 0], [0, -4], [-2, 0], [0, -8], 0, [-2, -8], [0, -2], [0, -6], [-2, -2]], dim = { height: (2 * o) + "px", width: (2 * o) + "px" }; for (var i = 0; i <= 8; i++) { if (pos[i]) { if (this.hasAlphaImageLoader) { var w = (i == 1 || i == 7) ? "100%" : this.graphic.width + "px"; var div = hs.createElement("div", null, { width: "100%", height: "100%", position: "relative", overflow: "hidden" }, this.td[i], true); hs.createElement("div", null, { filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='" + this.graphic.src + "')", position: "absolute", width: w, height: this.graphic.height + "px", left: (pos[i][0] * o) + "px", top: (pos[i][1] * o) + "px" }, div, true); } else { hs.setStyles(this.td[i], { background: "url(" + this.graphic.src + ") " + (pos[i][0] * o) + "px " + (pos[i][1] * o) + "px" }); } if (window.opera && (i == 3 || i == 5)) { hs.createElement("div", null, dim, this.td[i], true); } hs.setStyles(this.td[i], dim); } } hs.pendingOutlines[this.outlineType] = this; if (this.onLoad) { this.onLoad(); } }, setPosition: function (exp, x, y, w, h, vis) { if (vis) { this.table.style.visibility = (h >= 4 * this.offset) ? "visible" : "hidden"; } this.table.style.left = (x - this.offset) + "px"; this.table.style.top = (y - this.offset) + "px"; this.table.style.width = (w + 2 * (exp.offsetBorderW + this.offset)) + "px"; w += 2 * (exp.offsetBorderW - this.offset); h += +2 * (exp.offsetBorderH - this.offset); this.td[4].style.width = w >= 0 ? w + "px" : 0; this.td[4].style.height = h >= 0 ? h + "px" : 0; if (this.hasAlphaImageLoader) { this.td[3].style.height = this.td[5].style.height = this.td[4].style.height; } }, destroy: function (hide) { if (hide) { this.table.style.visibility = "hidden"; } else { hs.purge(this.table); try { this.table.parentNode.removeChild(this.table); } catch (e) { } } } }; hs.Expander = function (a, params, custom, contentType) { this.a = a; this.custom = custom; this.contentType = contentType || "image"; this.isImage = !this.isHtml; hs.continuePreloading = false; hs.genContainer(); var key = this.key = hs.expanders.length; for (var i = 0; i < hs.overrides.length; i++) { var name = hs.overrides[i]; this[name] = params && typeof params[name] != "undefined" ? params[name] : hs[name]; } var el = this.thumb = ((params && params.thumbnailId) ? hs.$(params.thumbnailId) : null) || a.getElementsByTagName("img")[0] || a; this.thumbsUserSetId = el.id || a.id; for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].a == a) { hs.expanders[i].focus(); return false; } } for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) { hs.expanders[i].cancelLoading(); } } hs.expanders[this.key] = this; if (!hs.allowMultipleInstances) { if (hs.expanders[key - 1]) { hs.expanders[key - 1].close(); } if (typeof hs.focusKey != "undefined" && hs.expanders[hs.focusKey]) { hs.expanders[hs.focusKey].close(); } } this.overlays = []; var pos = hs.position(el); this.thumbWidth = el.width ? el.width : el.offsetWidth; this.thumbHeight = el.height ? el.height : el.offsetHeight; this.thumbLeft = pos.x; this.thumbTop = pos.y; this.thumbOffsetBorderW = (this.thumb.offsetWidth - this.thumbWidth) / 2; this.thumbOffsetBorderH = (this.thumb.offsetHeight - this.thumbHeight) / 2; this.wrapper = hs.createElement("div", { id: "highslide-wrapper-" + this.key, className: this.wrapperClassName }, { visibility: "hidden", position: "absolute", zIndex: hs.zIndexCounter++ }, null, true); this.wrapper.onmouseover = function (e) { try { hs.expanders[key].wrapperMouseHandler(e); } catch (e) { } }; this.wrapper.onmouseout = function (e) { try { hs.expanders[key].wrapperMouseHandler(e); } catch (e) { } }; if (this.contentType == "image" && this.outlineWhileAnimating == 2) { this.outlineWhileAnimating = 0; } if (hs.pendingOutlines[this.outlineType]) { this.connectOutline(); this[this.contentType + "Create"](); } else { if (!this.outlineType) { this[this.contentType + "Create"](); } else { this.displayLoading(); var exp = this; new hs.Outline(this.outlineType, function () { exp.connectOutline(); exp[exp.contentType + "Create"](); }); } } return true; }; hs.Expander.prototype = { connectOutline: function (x, y) { var w = hs.pendingOutlines[this.outlineType]; this.objOutline = w; w.table.style.zIndex = this.wrapper.style.zIndex; hs.pendingOutlines[this.outlineType] = null; }, displayLoading: function () { if (this.onLoadStarted || this.loading) { return; } this.originalCursor = this.a.style.cursor; this.a.style.cursor = "wait"; this.loading = hs.loading; var exp = this; this.loading.onclick = function () { exp.cancelLoading(); }; this.loading.style.top = (this.thumbTop + (this.thumbHeight - this.loading.offsetHeight) / 2) + "px"; var exp = this, left = (this.thumbLeft + this.thumbOffsetBorderW + (this.thumbWidth - this.loading.offsetWidth) / 2) + "px"; setTimeout(function () { if (exp.loading) { exp.loading.style.left = left; } }, 100); }, imageCreate: function () { var exp = this; var img = document.createElement("img"); this.content = img; img.onload = function () { if (hs.expanders[exp.key]) { exp.contentLoaded(); } }; if (hs.blockRightClick) { img.oncontextmenu = function () { return false; }; } img.className = "highslide-image"; img.style.visibility = "hidden"; img.style.display = "block"; img.style.position = "absolute"; img.style.maxWidth = "none"; img.style.zIndex = 3; img.title = hs.restoreTitle; if (hs.safari) { hs.container.appendChild(img); } if (hs.ie && hs.flushImgSize) { img.src = null; } img.src = hs.getSrc(this.a); this.displayLoading(); }, contentLoaded: function () { try { if (!this.content) { return; } if (this.onLoadStarted) { return; } else { this.onLoadStarted = true; } if (this.loading) { this.loading.style.left = "-9999px"; this.loading = null; this.a.style.cursor = this.originalCursor || ""; } this.marginBottom = hs.marginBottom; this.newWidth = this.content.width; this.newHeight = this.content.height; this.fullExpandWidth = this.newWidth; this.fullExpandHeight = this.newHeight; this.content.style.width = this.thumbWidth + "px"; this.content.style.height = this.thumbHeight + "px"; this.getCaption(); this.wrapper.appendChild(this.content); this.content.style.position = "relative"; if (this.caption) { this.wrapper.appendChild(this.caption); } this.wrapper.style.left = this.thumbLeft + "px"; this.wrapper.style.top = this.thumbTop + "px"; hs.container.appendChild(this.wrapper); this.offsetBorderW = (this.content.offsetWidth - this.thumbWidth) / 2; this.offsetBorderH = (this.content.offsetHeight - this.thumbHeight) / 2; var modMarginRight = hs.marginRight + 2 * this.offsetBorderW; this.marginBottom += 2 * this.offsetBorderH; var ratio = this.newWidth / this.newHeight; var minWidth = this.allowSizeReduction ? this.minWidth : this.newWidth; var minHeight = this.allowSizeReduction ? this.minHeight : this.newHeight; var justify = { x: "auto", y: "auto" }; var page = hs.getPageSize(); this.x = { min: parseInt(this.thumbLeft) - this.offsetBorderW + this.thumbOffsetBorderW, span: this.newWidth, minSpan: (this.newWidth < minWidth && !hs.padToMinWidth) ? this.newWidth : minWidth, marginMin: hs.marginLeft, marginMax: modMarginRight, scroll: page.scrollLeft, clientSpan: page.width, thumbSpan: this.thumbWidth }; var oldRight = this.x.min + parseInt(this.thumbWidth); this.x = this.justify(this.x); this.y = { min: parseInt(this.thumbTop) - this.offsetBorderH + this.thumbOffsetBorderH, span: this.newHeight, minSpan: this.newHeight < minHeight ? this.newHeight : minHeight, marginMin: hs.marginTop, marginMax: this.marginBottom, scroll: page.scrollTop, clientSpan: page.height, thumbSpan: this.thumbHeight }; var oldBottom = this.y.min + parseInt(this.thumbHeight); this.y = this.justify(this.y); this.correctRatio(ratio); var x = this.x; var y = this.y; this.show(); } catch (e) { window.location.href = hs.getSrc(this.a); } }, justify: function (p) { var tgt, dim = p == this.x ? "x" : "y"; var hasMovedMin = false; var allowReduce = true; p.min = Math.round(p.min - ((p.span - p.thumbSpan) / 2)); if (p.min < p.scroll + p.marginMin) { p.min = p.scroll + p.marginMin; hasMovedMin = true; } if (p.span < p.minSpan) { p.span = p.minSpan; allowReduce = false; } if (p.min + p.span > p.scroll + p.clientSpan - p.marginMax) { if (hasMovedMin && allowReduce) { p.span = p.clientSpan - p.marginMin - p.marginMax; } else { if (p.span < p.clientSpan - p.marginMin - p.marginMax) { p.min = p.scroll + p.clientSpan - p.span - p.marginMin - p.marginMax; } else { p.min = p.scroll + p.marginMin; if (allowReduce) { p.span = p.clientSpan - p.marginMin - p.marginMax; } } } } if (p.span < p.minSpan) { p.span = p.minSpan; allowReduce = false; } if (p.min < p.marginMin) { tmpMin = p.min; p.min = p.marginMin; if (allowReduce) { p.span = p.span - (p.min - tmpMin); } } return p; }, correctRatio: function (ratio) { var x = this.x; var y = this.y; var changed = false; if (x.span / y.span > ratio) { var tmpWidth = x.span; x.span = y.span * ratio; if (x.span < x.minSpan) { if (hs.padToMinWidth) { x.imgSpan = x.span; } x.span = x.minSpan; if (!x.imgSpan) { y.span = x.span / ratio; } } changed = true; } else { if (x.span / y.span < ratio) { var tmpHeight = y.span; y.span = x.span / ratio; changed = true; } } if (changed) { x.min = parseInt(this.thumbLeft) - this.offsetBorderW + this.thumbOffsetBorderW; x.minSpan = x.span; this.x = this.justify(x); y.min = parseInt(this.thumbTop) - this.offsetBorderH + this.thumbOffsetBorderH; y.minSpan = y.span; this.y = this.justify(y); } }, show: function () { var imgPos = { x: this.x.min - 20, y: this.y.min - 20, w: this.x.span + 40, h: this.y.span + 40 + this.spaceForCaption }; hs.hideSelects = (hs.ie && hs.ieVersion() < 7); if (hs.hideSelects) { this.showHideElements("SELECT", "hidden", imgPos); } hs.hideIframes = ((window.opera && navigator.appVersion < 9) || navigator.vendor == "KDE" || (hs.ie && hs.ieVersion() < 5.5)); if (hs.hideIframes) { this.showHideElements("IFRAME", "hidden", imgPos); } if (hs.geckoMac) { this.showHideElements("*", "hidden", imgPos); } if (this.x.imgSpan) { this.content.style.margin = "0 auto"; } this.changeSize(1, { x: this.thumbLeft + this.thumbOffsetBorderW - this.offsetBorderW, y: this.thumbTop + this.thumbOffsetBorderH - this.offsetBorderH, w: this.thumbWidth, h: this.thumbHeight, imgW: this.thumbWidth, o: hs.outlineStartOffset }, { x: this.x.min, y: this.y.min, w: this.x.span, h: this.y.span, imgW: this.x.imgSpan, o: this.objOutline ? this.objOutline.offset : 0 }, hs.expandDuration, hs.expandSteps); }, changeSize: function (up, from, to, dur, steps) { if (up && this.objOutline && !this.outlineWhileAnimating) { this.objOutline.setPosition(this, this.x.min, this.y.min, this.x.span, this.y.span); } else { if (!up && this.objOutline) { if (this.outlineWhileAnimating) { this.objOutline.setPosition(this, from.x, from.y, from.w, from.h); } else { this.objOutline.destroy(); } } } if (!up) { var n = this.wrapper.childNodes.length; for (var i = n - 1; i >= 0; i--) { var child = this.wrapper.childNodes[i]; if (child != this.content) { hs.purge(child); this.wrapper.removeChild(child); } } } if (this.fadeInOut) { from.op = up ? 0 : 1; to.op = up; } var t, exp = this, easing = Math[this.easing] || Math.easeInQuad; if (!up) { easing = Math[this.easingClose] || easing; } for (var i = 1; i <= steps; i++) { t = Math.round(i * (dur / steps)); (function () { var pI = i, size = {}; for (var x in from) { size[x] = easing(t, from[x], to[x] - from[x], dur); } setTimeout(function () { if (up && pI == 1) { exp.content.style.visibility = "visible"; exp.a.className += " highslide-active-anchor"; } exp.setSize(size); }, t); })(); } if (up) { setTimeout(function () { if (exp.objOutline) { exp.objOutline.table.style.visibility = "visible"; } }, t); setTimeout(function () { if (exp.caption) { exp.writeCaption(); } exp.afterExpand(); }, t + 50); } else { setTimeout(function () { exp.afterClose(); }, t); } }, setSize: function (to) { try { this.wrapper.style.width = (to.w + 2 * this.offsetBorderW) + "px"; this.content.style.width = ((to.imgW && !isNaN(to.imgW)) ? to.imgW : to.w) + "px"; if (hs.safari) { this.content.style.maxWidth = this.content.style.width; } this.content.style.height = to.h + "px"; if (to.op) { hs.setStyles(this.wrapper, { opacity: to.op }); } if (this.objOutline && this.outlineWhileAnimating) { var o = this.objOutline.offset - to.o; this.objOutline.setPosition(this, to.x + o, to.y + o, to.w - 2 * o, to.h - 2 * o, 1); } hs.setStyles(this.wrapper, { "visibility": "visible", "left": to.x + "px", "top": to.y + "px" }); } catch (e) { window.location.href = hs.getSrc(this.a); } }, afterExpand: function () { this.isExpanded = true; this.focus(); this.createOverlays(); if (hs.showCredits) { this.writeCredits(); } if (this.isImage && this.fullExpandWidth > this.x.span) { this.createFullExpand(); } if (!this.caption) { this.prepareNextOutline(); } }, prepareNextOutline: function () { var key = this.key; var outlineType = this.outlineType; new hs.Outline(outlineType, function () { try { hs.expanders[key].preloadNext(); } catch (e) { } }); }, preloadNext: function () { var next = hs.getAdjacentAnchor(this.key, 1); if (next.onclick.toString().match(/hs\.expand/)) { var img = hs.createElement("img", { src: hs.getSrc(next) }); } }, cancelLoading: function () { hs.expanders[this.key] = null; this.a.style.cursor = this.originalCursor; if (this.loading) { hs.loading.style.left = "-9999px"; } }, writeCredits: function () { var credits = hs.createElement("a", { href: hs.creditsHref, className: "highslide-credits", innerHTML: hs.creditsText, title: hs.creditsTitle }); this.createOverlay({ overlayId: credits, position: "top left" }); }, getCaption: function () { if (!this.captionId && this.thumbsUserSetId) { this.captionId = "caption-for-" + this.thumbsUserSetId; } if (this.captionId) { this.caption = hs.getNode(this.captionId); } if (!this.caption && !this.captionText && this.captionEval) { try { this.captionText = eval(this.captionEval); } catch (e) { } } if (!this.caption && this.captionText) { this.caption = hs.createElement("div", { className: "highslide-caption", innerHTML: this.captionText }); } if (!this.caption) { var next = this.a.nextSibling; while (next && !hs.isHsAnchor(next)) { if (/highslide-caption/.test(next.className || null)) { this.caption = next.cloneNode(1); break; } next = next.nextSibling; } } if (this.caption) { this.marginBottom += this.spaceForCaption; } }, writeCaption: function () { try { hs.setStyles(this.wrapper, { width: this.wrapper.offsetWidth + "px", height: this.wrapper.offsetHeight + "px" }); hs.setStyles(this.caption, { visibility: "hidden", marginTop: hs.safari ? 0 : "-" + this.y.span + "px" }); this.caption.className += " highslide-display-block"; var height, exp = this; if (hs.ie && (hs.ieVersion() < 6 || document.compatMode == "BackCompat")) { height = this.caption.offsetHeight; } else { var temp = hs.createElement("div", { innerHTML: this.caption.innerHTML }, null, null, true); this.caption.innerHTML = ""; this.caption.appendChild(temp); height = this.caption.childNodes[0].offsetHeight; this.caption.innerHTML = this.caption.childNodes[0].innerHTML; } hs.setStyles(this.caption, { overflow: "hidden", height: 0, zIndex: 2, marginTop: 0 }); this.wrapper.style.height = "auto"; if (hs.captionSlideSpeed) { var step = (Math.round(height / 50) || 1) * hs.captionSlideSpeed; } else { this.placeCaption(height, 1); return; } for (var h = height % step, t = 0; h <= height; h += step, t += 10) { (function () { var pH = h, end = (h == height) ? 1 : 0; setTimeout(function () { exp.placeCaption(pH, end); }, t); })(); } } catch (e) { } }, placeCaption: function (height, end) { if (!this.caption) { return; } this.caption.style.height = height + "px"; this.caption.style.visibility = "visible"; this.y.span = this.wrapper.offsetHeight - 2 * this.offsetBorderH; var o = this.objOutline; if (o) { o.td[4].style.height = (this.wrapper.offsetHeight - 2 * this.objOutline.offset) + "px"; if (o.hasAlphaImageLoader) { o.td[3].style.height = o.td[5].style.height = o.td[4].style.height; } } if (end) { this.prepareNextOutline(); } }, showHideElements: function (tagName, visibility, imgPos) { var els = document.getElementsByTagName(tagName); var prop = tagName == "*" ? "overflow" : "visibility"; for (var i = 0; i < els.length; i++) { if (prop == "visibility" || (document.defaultView.getComputedStyle(els[i], "").getPropertyValue("overflow") == "auto" || els[i].getAttribute("hidden-by") != null)) { var hiddenBy = els[i].getAttribute("hidden-by"); if (visibility == "visible" && hiddenBy) { hiddenBy = hiddenBy.replace("[" + this.key + "]", ""); els[i].setAttribute("hidden-by", hiddenBy); if (!hiddenBy) { els[i].style[prop] = els[i].origProp; } } else { if (visibility == "hidden") { var elPos = hs.position(els[i]); elPos.w = els[i].offsetWidth; elPos.h = els[i].offsetHeight; var clearsX = (elPos.x + elPos.w < imgPos.x || elPos.x > imgPos.x + imgPos.w); var clearsY = (elPos.y + elPos.h < imgPos.y || elPos.y > imgPos.y + imgPos.h); var wrapperKey = hs.getWrapperKey(els[i]); if (!clearsX && !clearsY && wrapperKey != this.key) { if (!hiddenBy) { els[i].setAttribute("hidden-by", "[" + this.key + "]"); els[i].origProp = els[i].style[prop]; els[i].style[prop] = "hidden"; } else { if (!hiddenBy.match("[" + this.key + "]")) { els[i].setAttribute("hidden-by", hiddenBy + "[" + this.key + "]"); } } } else { if (hiddenBy == "[" + this.key + "]" || hs.focusKey == wrapperKey) { els[i].setAttribute("hidden-by", ""); els[i].style[prop] = els[i].origProp || ""; } else { if (hiddenBy && hiddenBy.match("[" + this.key + "]")) { els[i].setAttribute("hidden-by", hiddenBy.replace("[" + this.key + "]", "")); } } } } } } } }, focus: function () { this.wrapper.style.zIndex = hs.zIndexCounter++; for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && i == hs.focusKey) { var blurExp = hs.expanders[i]; blurExp.content.className += " highslide-" + blurExp.contentType + "-blur"; if (blurExp.caption) { blurExp.caption.className += " highslide-caption-blur"; } blurExp.content.style.cursor = hs.ie ? "hand" : "pointer"; blurExp.content.title = hs.focusTitle; } } if (this.objOutline) { this.objOutline.table.style.zIndex = this.wrapper.style.zIndex; } this.content.className = "highslide-" + this.contentType; if (this.caption) { this.caption.className = this.caption.className.replace(" highslide-caption-blur", ""); } this.content.title = hs.restoreTitle; hs.styleRestoreCursor = window.opera ? "pointer" : "url(" + hs.graphicsDir + hs.restoreCursor + "), pointer"; if (hs.ie && hs.ieVersion() < 6) { hs.styleRestoreCursor = "hand"; } this.content.style.cursor = hs.styleRestoreCursor; hs.focusKey = this.key; hs.addEventListener(document, "keydown", hs.keyHandler); }, move: function (e) { this.x.min = e.left + e.dX; this.y.min = e.top + e.dY; if (e.type == "image") { this.content.style.cursor = "move"; } hs.setStyles(this.wrapper, { left: this.x.min + "px", top: this.y.min + "px" }); if (this.objOutline) { this.objOutline.setPosition(this, this.x.min, this.y.min, this.x.span, this.y.span); } }, close: function () { if (this.isClosing || !this.isExpanded) { return; } this.isClosing = true; hs.removeEventListener(document, "keydown", hs.keyHandler); try { this.content.style.cursor = "default"; this.changeSize(0, { x: this.x.min, y: this.y.min, w: this.x.span, h: parseInt(this.content.style.height), imgW: this.x.imgSpan, o: this.objOutline ? this.objOutline.offset : 0 }, { x: this.thumbLeft - this.offsetBorderW + this.thumbOffsetBorderW, y: this.thumbTop - this.offsetBorderH + this.thumbOffsetBorderH, w: this.thumbWidth, h: this.thumbHeight, imgW: this.thumbWidth, o: hs.outlineStartOffset }, hs.restoreDuration, hs.restoreSteps); } catch (e) { this.afterClose(); } }, createOverlay: function (o) { var el = o.overlayId; if (typeof el == "string") { el = hs.getNode(el); } if (!el || typeof el == "string") { return; } var overlay = hs.createElement("div", null, { "left": 0, "top": 0, "position": "absolute", "zIndex": 3, "visibility": "hidden" }, this.wrapper, true); if (o.opacity) { hs.setStyles(el, { opacity: o.opacity }); } el.style.styleFloat = "none"; el.className += " highslide-display-block"; overlay.appendChild(el); overlay.hsPos = o.position; this.positionOverlay(overlay); if (o.hideOnMouseOut) { overlay.setAttribute("hideOnMouseOut", true); } if (!o.opacity) { o.opacity = 1; } overlay.setAttribute("opacity", o.opacity); hs.fade(overlay, 0, o.opacity); hs.push(this.overlays, overlay); }, positionOverlay: function (overlay) { var left = this.offsetBorderW; var dLeft = this.x.span - overlay.offsetWidth; var top = this.offsetBorderH; var dTop = parseInt(this.content.style.height) - overlay.offsetHeight; var p = overlay.hsPos || "center center"; if (/^bottom/.test(p)) { top += dTop; } if (/^center/.test(p)) { top += dTop / 2; } if (/right$/.test(p)) { left += dLeft; } if (/center$/.test(p)) { left += dLeft / 2; } overlay.style.left = left + "px"; overlay.style.top = top + "px"; }, createOverlays: function () { for (var i = 0; i < hs.overlays.length; i++) { var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup; if ((!tId && !sg) || tId == this.thumbsUserSetId || sg === this.slideshowGroup) { this.createOverlay(o); } } }, createFullExpand: function () { var a = hs.createElement("a", { href: "javascript:hs.expanders[" + this.key + "].doFullExpand();", title: hs.fullExpandTitle, className: "highslide-full-expand" }); this.fullExpandLabel = a; this.createOverlay({ overlayId: a, position: hs.fullExpandPosition, hideOnMouseOut: true, opacity: hs.fullExpandOpacity }); }, doFullExpand: function () { try { hs.purge(this.fullExpandLabel); this.fullExpandLabel.parentNode.removeChild(this.fullExpandLabel); this.focus(); this.x.min = parseInt(this.wrapper.style.left) - (this.fullExpandWidth - this.content.width) / 2; if (this.x.min < hs.marginLeft) { this.x.min = hs.marginLeft; } this.wrapper.style.left = this.x.min + "px"; hs.setStyles(this.content, { width: this.fullExpandWidth + "px", height: this.fullExpandHeight + "px" }); this.x.span = this.fullExpandWidth; this.wrapper.style.width = (this.x.span + 2 * this.offsetBorderW) + "px"; this.y.span = this.wrapper.offsetHeight - 2 * this.offsetBorderH; if (this.objOutline) { this.objOutline.setPosition(this, this.x.min, this.y.min, this.x.span, this.y.span); } for (var i = 0; i < this.overlays.length; i++) { this.positionOverlay(this.overlays[i]); } this.redoShowHide(); } catch (e) { window.location.href = this.content.src; } }, redoShowHide: function () { var imgPos = { x: parseInt(this.wrapper.style.left) - 20, y: parseInt(this.wrapper.style.top) - 20, w: this.content.offsetWidth + 40, h: this.content.offsetHeight + 40 + this.spaceForCaption }; if (hs.hideSelects) { this.showHideElements("SELECT", "hidden", imgPos); } if (hs.hideIframes) { this.showHideElements("IFRAME", "hidden", imgPos); } if (hs.geckoMac) { this.showHideElements("*", "hidden", imgPos); } }, wrapperMouseHandler: function (e) { if (!e) { e = window.event; } var over = /mouseover/i.test(e.type); if (!e.target) { e.target = e.srcElement; } if (hs.ie) { e.relatedTarget = over ? e.fromElement : e.toElement; } if (hs.getExpander(e.relatedTarget) == this || hs.dragArgs) { return; } for (var i = 0; i < this.overlays.length; i++) { var o = this.overlays[i]; if (o.getAttribute("hideOnMouseOut")) { var from = over ? 0 : o.getAttribute("opacity"), to = over ? o.getAttribute("opacity") : 0; hs.fade(o, from, to); } } }, afterClose: function () { this.a.className = this.a.className.replace("highslide-active-anchor", ""); if (hs.hideSelects) { this.showHideElements("SELECT", "visible"); } if (hs.hideIframes) { this.showHideElements("IFRAME", "visible"); } if (hs.geckoMac) { this.showHideElements("*", "visible"); } if (this.objOutline && this.outlineWhileAnimating) { this.objOutline.destroy(); } hs.purge(this.wrapper); if (hs.ie && hs.ieVersion() < 5.5) { this.wrapper.innerHTML = ""; } else { this.wrapper.parentNode.removeChild(this.wrapper); } hs.expanders[this.key] = null; hs.cleanUp(); } }; var HsExpander = hs.Expander; hs.addEventListener(document, "mousedown", hs.mouseClickHandler); hs.addEventListener(document, "mouseup", hs.mouseClickHandler); hs.addEventListener(window, "load", hs.preloadImages);


/******************************************************************************
Chrome Drop Down Menu v2.01- Author: Dynamic Drive (http://www.dynamicdrive.com)
Last updated: November 14th 06- added iframe shim technique
******************************************************************************/
// Chrome Drop Down Menu: /scripts/header.js
var cssdropdown = { disappeardelay: 200, appeardelay: 300, disablemenuclick: false, enableswipe: 0, dropmenuobj: null, ie: document.all, firefox: document.getElementById && !document.all, swipetimer: undefined, bottomclip: 0, getposOffset: function (what, offsettype) { var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop; var parentEl = what.offsetParent; while (parentEl != null) { totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop; parentEl = parentEl.offsetParent; } return totaloffset; }, swipeeffect: function () { if (this.bottomclip < parseInt(this.dropmenuobj.offsetHeight)) { this.bottomclip += 10 + (this.bottomclip / 10); this.dropmenuobj.style.clip = "rect(0 auto " + this.bottomclip + "px 0)"; } else { return; } this.swipetimer = setTimeout("cssdropdown.swipeeffect()", 20); }, showhide: function (obj, e) { if (this.ie || this.firefox) { this.dropmenuobj.style.left = this.dropmenuobj.style.top = "-500px"; } if (e.type == "click" && obj.visibility == hidden || e.type == "mouseover") { if (this.enableswipe == 1) { if (typeof this.swipetimer != "undefined") { clearTimeout(this.swipetimer); } obj.clip = "rect(0 auto 0 0)"; this.bottomclip = 0; setTimeout("cssdropdown.swipeeffect()", this.appeardelay); } this.delayshowmenu(); } else { if (e.type == "click") { obj.visibility = "hidden"; } } }, iecompattest: function () { return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body; }, clearbrowseredge: function (obj, whichedge) { var edgeoffset = 0; if (whichedge == "rightedge") { var windowedge = this.ie && !window.opera ? this.iecompattest().scrollLeft + this.iecompattest().clientWidth - 15 : window.pageXOffset + window.innerWidth - 15; this.dropmenuobj.contentmeasure = this.dropmenuobj.offsetWidth; if (windowedge - this.dropmenuobj.x < this.dropmenuobj.contentmeasure) { edgeoffset = this.dropmenuobj.contentmeasure - obj.offsetWidth; } } else { var topedge = this.ie && !window.opera ? this.iecompattest().scrollTop : window.pageYOffset; var windowedge = this.ie && !window.opera ? this.iecompattest().scrollTop + this.iecompattest().clientHeight - 15 : window.pageYOffset + window.innerHeight - 18; this.dropmenuobj.contentmeasure = this.dropmenuobj.offsetHeight; if (windowedge - this.dropmenuobj.y < this.dropmenuobj.contentmeasure) { edgeoffset = this.dropmenuobj.contentmeasure + obj.offsetHeight; if ((this.dropmenuobj.y - topedge) < this.dropmenuobj.contentmeasure) { edgeoffset = this.dropmenuobj.y + obj.offsetHeight - topedge; } } } return edgeoffset; }, dropit: function (obj, e, dropmenuID) { if (this.dropmenuobj != null) { this.dropmenuobj.style.visibility = "hidden"; } this.clearhidemenu(); if (this.ie || this.firefox) { obj.onmouseout = function () { cssdropdown.delayhidemenu(); cssdropdown.clearshowmenu(); }; obj.onclick = function () { return !cssdropdown.disablemenuclick; }; this.dropmenuobj = document.getElementById(dropmenuID); this.dropmenuobj.onmouseover = function () { cssdropdown.clearhidemenu(); }; this.dropmenuobj.onmouseout = function () { cssdropdown.dynamichide(e); }; this.dropmenuobj.onclick = function () { cssdropdown.delayhidemenu(); }; this.showhide(this.dropmenuobj.style, e); this.dropmenuobj.x = this.getposOffset(obj, "left"); this.dropmenuobj.y = this.getposOffset(obj, "top"); this.dropmenuobj.style.left = this.dropmenuobj.x - this.clearbrowseredge(obj, "rightedge") + "px"; this.dropmenuobj.style.top = this.dropmenuobj.y - this.clearbrowseredge(obj, "bottomedge") + obj.offsetHeight + 1 + "px"; } }, contains_firefox: function (a, b) { while (b.parentNode) { if ((b = b.parentNode) == a) { return true; } } return false; }, dynamichide: function (e) { var evtobj = window.event ? window.event : e; if (this.ie && !this.dropmenuobj.contains(evtobj.toElement)) { this.delayhidemenu(); } else { if (this.firefox && e.currentTarget != evtobj.relatedTarget && !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget)) { this.delayhidemenu(); } } }, delayhidemenu: function () { this.delayhide = setTimeout("cssdropdown.dropmenuobj.style.visibility='hidden'", this.disappeardelay); }, clearhidemenu: function () { if (this.delayhide != "undefined") { clearTimeout(this.delayhide); } }, delayshowmenu: function () { this.delayshow = setTimeout("cssdropdown.dropmenuobj.style.visibility='visible'", this.appeardelay); }, clearshowmenu: function () { if (this.delayshow != "undefined") { clearTimeout(this.delayshow); } }, startchrome: function () { for (var ids = 0; ids < arguments.length; ids++) { var menuitems = document.getElementById(arguments[ids]).getElementsByTagName("a"); for (var i = 0; i < menuitems.length; i++) { if (menuitems[i].getAttribute("rel")) { var relvalue = menuitems[i].getAttribute("rel"); menuitems[i].onmouseover = function (e) { var event = typeof e != "undefined" ? e : window.event; cssdropdown.dropit(this, event, this.getAttribute("rel")); }; } } } } };


/******************************************************************************
@author:    Danny Ng (http://www.dannytalk.com/2010/08/19/read-google-an…-cookie-script/)
@modified:  19/08/10
@notes:     Free to use and distribute without altering this comment. Would appreciate a link back :)
******************************************************************************/
/// Google Cookie: /App_Scripts/gCookies.js
String.prototype.trim = function () { return this.replace(/^\s*|\s*$/g, ""); }; String.prototype.empty = function () { if (this.length == 0) { return true; } else { if (this.length > 0) { return /^\s*$/.test(this); } } }; function crumbleCookie(c) { var cookie_array = document.cookie.split(";"); var keyvaluepair = {}; for (var cookie = 0; cookie < cookie_array.length; cookie++) { var key = cookie_array[cookie].substring(0, cookie_array[cookie].indexOf("=")).trim(); var value = cookie_array[cookie].substring(cookie_array[cookie].indexOf("=") + 1, cookie_array[cookie].length).trim(); keyvaluepair[key] = value; } if (c) { return keyvaluepair[c] ? keyvaluepair[c] : null; } return keyvaluepair; } function gaCookies() { var utma = function () { var utma_array; if (crumbleCookie("__utma")) { utma_array = crumbleCookie("__utma").split("."); } else { return null; } var domainhash = utma_array[0]; var uniqueid = utma_array[1]; var ftime = utma_array[2]; var ltime = utma_array[3]; var stime = utma_array[4]; var sessions = utma_array[5]; return { "cookie": utma_array, "domainhash": domainhash, "uniqueid": uniqueid, "ftime": ftime, "ltime": ltime, "stime": stime, "sessions": sessions }; }; var utmb = function () { var utmb_array; if (crumbleCookie("__utmb")) { utmb_array = crumbleCookie("__utmb").split("."); } else { return null; } var gifrequest = utmb_array[1]; return { "cookie": utmb_array, "gifrequest": gifrequest }; }; var utmv = function () { var utmv_array; if (crumbleCookie("__utmv")) { utmv_array = crumbleCookie("__utmv").split("."); } else { return null; } var value = utmv_array[1]; return { "cookie": utmv_array, "value": value }; }; var utmz = function () { var utmz_array, source, medium, name, term, content, gclid; if (crumbleCookie("__utmz")) { utmz_array = crumbleCookie("__utmz").split("."); } else { return null; } var utms = utmz_array[4].split("|"); for (var i = 0; i < utms.length; i++) { var key = utms[i].substring(0, utms[i].indexOf("=")); var val = decodeURIComponent(utms[i].substring(utms[i].indexOf("=") + 1, utms[i].length)); val = val.replace(/^\(|\)$/g, ""); switch (key) { case "utmcsr": source = val; break; case "utmcmd": medium = val; break; case "utmccn": name = val; break; case "utmctr": term = val; break; case "utmcct": content = val; break; case "utmgclid": gclid = val; break; } } return { "cookie": utmz_array, "source": source, "medium": medium, "name": name, "term": term, "content": content, "gclid": gclid }; }; this.getDomainHash = function () { return (utma() && utma().domainhash) ? utma().domainhash : null; }; this.getUniqueId = function () { return (utma() && utma().uniqueid) ? utma().uniqueid : null; }; this.getInitialVisitTime = function () { return (utma() && utma().ftime) ? utma().ftime : null; }; this.getPreviousVisitTime = function () { return (utma() && utma().ltime) ? utma().ltime : null; }; this.getCurrentVisitTime = function () { return (utma() && utma().stime) ? utma().stime : null; }; this.getSessionCounter = function () { return (utma() && utma().sessions) ? utma().sessions : null; }; this.getGifRequests = function () { return (utmb() && utmb().gifrequest) ? utmb().gifrequest : null; }; this.getUserDefinedValue = function () { return (utmv() && utmv().value) ? decodeURIComponent(utmv().value) : null; }; this.getCampaignSource = function () { return (utmz() && utmz().source) ? utmz().source : null; }; this.getCampaignMedium = function () { return (utmz() && utmz().medium) ? utmz().medium : null; }; this.getCampaignName = function () { return (utmz() && utmz().name) ? utmz().name : null; }; this.getCampaignTerm = function () { return (utmz() && utmz().term) ? utmz().term : null; }; this.getCampaignContent = function () { return (utmz() && utmz().content) ? utmz().content : null; }; this.getGclid = function () { return (utmz() && utmz().gclid) ? utmz().gclid : null; }; }




<!-- This script is based on the javascript code of Roman Feldblum (web.developer@programmer.net) -->
<!-- Original script : http://javascript.internet.com/forms/format-phone-number.html -->
<!-- Original script is revised by Eralper Yilmaz (http://www.eralper.com) -->
<!-- Revised script : http://www.kodyaz.com -->
<!-- Format : "(123) 456-7890" -->

var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 14;
var phonevalue1;
var phonevalue2;
var cursorposition;

function ParseForNumber1(object){
  phonevalue1 = ParseChar(object.value, zChar);
}

function ParseForNumber2(object){
  phonevalue2 = ParseChar(object.value, zChar);
}

function backspacerUP(object,e) {
  if(e){
    e = e
  } else {
    e = window.event
  }
  if(e.which){
    var keycode = e.which
  } else {
    var keycode = e.keyCode
  }

  ParseForNumber1(object)

  if(keycode >= 48){
    ValidatePhone(object)
  }
}

function backspacerDOWN(object,e) {
  if(e){
    e = e
  } else {
    e = window.event
  }
  if(e.which){
    var keycode = e.which
  } else {
    var keycode = e.keyCode
  }
  ParseForNumber2(object)
}

function GetCursorPosition(){

  var t1 = phonevalue1;
  var t2 = phonevalue2;
  var bool = false
  for (i=0; i<t1.length; i++)
  {
    if (t1.substring(i,1) != t2.substring(i,1)) {
      if(!bool) {
        cursorposition=i
        window.status=cursorposition
        bool=true
      }
    }
  }
}

function ValidatePhone(object){

  var p = phonevalue1

  p = p.replace(/[^\d]*/gi,"")

  if (p.length < 3) {
    object.value=p
  } else if(p.length==3){
    pp=p;
    d4=p.indexOf('(')
    d5=p.indexOf(')')
    if(d4==-1){
      pp="("+pp;
    }
    if(d5==-1){
      pp=pp+")";
    }
    object.value = pp;
  } else if(p.length>3 && p.length < 7){
    p ="(" + p;
    l30=p.length;
    p30=p.substring(0,4);
    p30=p30+") "

    p31=p.substring(4,l30);
    pp=p30+p31;

    object.value = pp;

  } else if(p.length >= 7){
    p ="(" + p;
    l30=p.length;
    p30=p.substring(0,4);
    p30=p30+") "

    p31=p.substring(4,l30);
    pp=p30+p31;

    l40 = pp.length;
    p40 = pp.substring(0,9);
    p40 = p40 + "-"

    p41 = pp.substring(9,l40);
    ppp = p40 + p41;

    object.value = ppp.substring(0, maxphonelength);
  }

  GetCursorPosition()

  if(cursorposition >= 0){
    if (cursorposition == 0) {
      cursorposition = 2
    } else if (cursorposition <= 2) {
      cursorposition = cursorposition + 1
    } else if (cursorposition <= 4) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 5) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 6) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 7) {
      cursorposition = cursorposition + 4
    } else if (cursorposition == 8) {
      cursorposition = cursorposition + 4
      e1=object.value.indexOf(')')
      e2=object.value.indexOf('-')
      if (e1>-1 && e2>-1){
        if (e2-e1 == 4) {
          cursorposition = cursorposition - 1
        }
      }
    } else if (cursorposition == 9) {
      cursorposition = cursorposition + 4
    } else if (cursorposition < 11) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 11) {
      cursorposition = cursorposition + 1
    } else if (cursorposition == 12) {
      cursorposition = cursorposition + 1
    } else if (cursorposition >= 13) {
      cursorposition = cursorposition
    }
	if(object.createTextRange()){
    var txtRange = object.createTextRange();
    txtRange.moveStart( "character", cursorposition);
    txtRange.moveEnd( "character", cursorposition - object.value.length);
    txtRange.select();
	}
  }

}

function ParseChar(sStr, sChar)
{

  if (sChar.length == null)
  {
    zChar = new Array(sChar);
  }
    else zChar = sChar;

  for (i=0; i<zChar.length; i++)
  {
    sNewStr = "";

    var iStart = 0;
    var iEnd = sStr.indexOf(sChar[i]);

    while (iEnd != -1)
    {
      sNewStr += sStr.substring(iStart, iEnd);
      iStart = iEnd + 1;
      iEnd = sStr.indexOf(sChar[i], iStart);
    }
    sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);

    sStr = sNewStr;
  }

  return sNewStr;
}


/******************************************
*                                         *
*           End 3rd party code            *
*                                         *
*                                         *
*******************************************/
