/**********************************************************
Author:
Adam Barry
eBOUND
www.ebound.dk

Date: January 4 2008

� 2008 Adam Barry, all rights reserved
-----------------------------------------------------------

Name:
shoppingCart script

-----------------------------------------------------------
Description:
Scripts used for the shopping cart including moving and
flashing mini-cart, closing of full cart when the escape
key is pressed etc.

-----------------------------------------------------------
Usage:
Simply place a link to the this script in the head-section
of the XHTML page. The script will then automatically
execute on page load.

<script type="text/javascript" src="shoppingCart.js"></script>

-----------------------------------------------------------
Example:
<script type="text/javascript" src="shoppingCart.js"></script>

<dl class="cart">
<dt><span>Shopping cart overview</span></dt>
<dd>Items: <span>4</span></dd>
<dd>Sub total: <span>DKK 400</span></dd>
<dd><a>View shopping cart</a></dd>
</dl>


<div class="cartContainer">

<div class="wrapper">

<div class="cart">

<h2>Shopping cart</h2>
<a class="cartHide"><span>Return to shop</span></a>

<p class="notification">You have just removed an item from your shopping cart. <a><span>Undo removal</span></a></p>

<table class="cart">
<thead>
<tr>
<th>Item#</th>
<th class="description">Description</th>
<th>Item price</th>
<th class="qty">Qty</th>
<th class="total">Total</th>
<th class="functions"></th>
</tr>
</thead>

<tfoot>
<tr>
<td colspan="3"></td>
<td class="sub">Sub total</td>
<td class="total">DKK 400</td>
</tr>
<tr class="shipping">
<td colspan="4">
Estimated shipping cost to
<select>
<option>Choose country</option>
<option selected="selected">Denmark</option>
</select>
</td>
<td class="total">DKK 50</td>
</tr>
<tr class="vat">
<td colspan="3"></td>
<td class="sub">VAT 25 %</td>
<td class="total">DKK 100</td>
</tr>
<tr class="total">
<td colspan="3"></td>
<td class="sub">Total cost</td>
<td class="total">DKK 550</td>
</tr>
</tfoot>

<tbody>
<tr>
<td>1</td>
<td class="description">T-shirt</td>
<td>DKK 100</td>
<td class="qty"><input type="text" value="2" /></td>
<td class="total">DKK 200</td>
<td class="functions"><a class="remove" href="#" title="Remove this item"><span>Remove</span></a></td>
</tr>
<tr>
<td>2</td>
<td class="description">Vestibulum ac nisl. Curabitur aliquet tortor ac leo. Aliquam erat volutpat. Maecenas a augue. Ut quis velit. Ut orci augue, sollicitudin iaculis, laoreet vel, vestibulum sit amet, mi.</td>
<td>DKK 100</td>
<td class="qty"><input type="text" value="2" /></td>
<td class="total">DKK 200</td>
<td class="functions"><a class="remove" href="#" title="Remove this item"><span>Remove</span></a></td>
</tr>
</tbody>
</table>

<button class="continueShopping"><span><span><span>Return to shop</span></span></span></button>
<button class="checkOut"><span><span><span>Proceed to checkout</span></span></span></button>

</div>

</div>

</div>

-----------------------------------------------------------
Dependencies:
This script depends on the windowOnLoad-script to execute

**********************************************************/

var cartContainer;
var miniCart;

function initShoppingCart() {
    if (!document.getElementsByTagName) return;

    var divs = document.getElementsByTagName("div");

    for (var i = 0; i < divs.length; i++) {
        if (divs[i].className.indexOf('cartContainer') == 0) {
            cartContainer = divs[i];
        }
    }
    if (!cartContainer) return;


    var togglers = document.getElementsByTagName("dl");

    for (var i = 0; i < togglers.length; i++) {
        var toggler = togglers[i];

        if (toggler.className.indexOf('miniCart') == 0) {
            miniCart = toggler;
            toggler.onclick = function () {
                toggleCart();
            }
        }
    }

    var togglers = document.getElementsByTagName("a");

    for (var i = 0; i < togglers.length; i++) {
        if (togglers[i].className.indexOf('cartHide') == 0) {
            togglers[i].onclick = function () {
                closeCart();
            }
        }
    }

    var togglers = document.getElementsByTagName("button");

    for (var i = 0; i < togglers.length; i++) {
        if (togglers[i].className.indexOf('continueShopping') == 0) {
            togglers[i].onclick = function () {
                closeCart();
            }
        }
    }
}
addLoadEvent(function () { initShoppingCart(); });


function toggleCart() {
    if (cartContainer.className.indexOf('selected') < 0) {
        refreshBasket();
        cartContainer.className += " selected";
    }
    else {
        cartContainer.className = cartContainer.className.replace(new RegExp("selected\\b"), "");
    }
}

function closeCart() {
    cartContainer.className = "cartContainer";
    refreshSmallBasket();
}


/*********************************************************
Name:
Mini-cart movement script

-----------------------------------------------------------
Description:
Functions that makes the mini-cart stay in the top of the
browser window at all times. The movement is animated to
create af smoother experience.

The script adds it self to the window.onscroll events
handler which is not support by all current browsers. This
means that browsers that do not support window.onscroll
will leave mini-cart in the top of the screen, where it
was initially placed.

-----------------------------------------------------------
Compatability:
The script is tested compatible with the following browsers:
- Internet Explorer 6
- Internet Explorer 7
- Firefox 2.0.0.3
- Opera 9.10
- Safari 2.0.4

Not compatible with:
- Firefox 1.5

-----------------------------------------------------------
Dependencies:
This script depends on the windowOnLoad-script and
shoppingCart-script to execute

**********************************************************/

var startingPoint;

function initMiniCartMovement() {
    if (!miniCart) return;

    /* Calculate the vertical starting-point for the mini-cart */
    startingPoint = getVPos() - 10;
    animateCart();

    /* Make sure the mini-cart follows window-scrolling */
    window.onscroll = function () {
        animateCart();
    }
}

function getVPos() {
    /* Get the vertical position of the mini-cart */
    var scrolled;
    if (document.documentElement && document.documentElement.scrollTop) { scrolled = document.documentElement.scrollTop; } //Sniffing for IE5
    else if (document.body) { scrolled = document.body.scrollTop; } //Sniffing for IE6
    else { scrolled = window.pageYOffset; } //Sniffing for Netscape
    return scrolled;
}

function move(cordY) {
    miniCart.style.top = cordY + "px";
}

function animateCart() {
    var destinationPoint = getVPos();
    var wait = 350;

    if (startingPoint <= destinationPoint) {
        for (var i = startingPoint; i <= destinationPoint; i++) {
            setTimeout("move(" + i + ")", wait);
        }
        startingPoint = destinationPoint;
    }

    else {
        for (var i = startingPoint; i >= destinationPoint; i--) {
            setTimeout("move(" + i + ")", wait);
        }
        startingPoint = destinationPoint;
    }
}
addLoadEvent(function () { initMiniCartMovement(); });


/*********************************************************
Name:
flash-cart script

-----------------------------------------------------------
Description:
Function that flashes the mini-cart when the function is
called.

-----------------------------------------------------------
Compatability:
The script is tested compatible with the following browsers:
- Internet Explorer 6
- Internet Explorer 7
- Firefox 2.0.0.3
- Safari 3

Not compatible with;
- Opera 9.10

-----------------------------------------------------------
Dependencies:
None

**********************************************************/

var flashing = false; 	/* Mutex that checks if the mini-cart is currently flashing */
var noOfTimes = 2; 	/* Number of times to flash the mini-cart */
flashTime = 500; 	/* 1 sek. = 1000 */

function flashCart() {
    setTimeout("toggleCartSelection()");

    if (noOfTimes < 0) {
        noOfTimes = 2;
        flashing = false;
        return;
    }

    noOfTimes = noOfTimes - 1;
    setTimeout("flashCart()", flashTime);
}

function toggleCartSelection() {
    if (miniCart.className.indexOf('selected') < 0) {
        miniCart.className += " selected";
    }
    else {
        miniCart.className = "miniCart";
    }
}


/*********************************************************
Name:
addToCart script

-----------------------------------------------------------
Description:
Function that handles the event of a customer adding an
item to the shopping cart.

-----------------------------------------------------------
Compatability:

-----------------------------------------------------------
Dependencies:
This script depends on the xmlhttp (AJAX) script script to
execute

**********************************************************/

function addToCart(id) {
    /* Add an item to the shopping cart using AJAX */

    var quantity;
    if (document.getElementById('quantity') && document.getElementById('quantity').value >= 1) {
        quantity = document.getElementById('quantity').value;
    }
    else {
        quantity = 1;
    }

    var size = '';
    var text = '';
    var font = '';

    if (document.getElementById('size')) {
        size = document.getElementById('size').value
    }
    if (document.getElementById('text')) {
        text = encodeURI(document.getElementById('text').value);
    }
    if (document.getElementById('font')) {
        font = document.getElementById('font').options[document.getElementById('font').selectedIndex].text;
    }

    var size2 = '';
    var text2 = '';
    var font2 = '';
    if (document.getElementById('size1')) {
        size2 = document.getElementById('size1').value
    }
    if (document.getElementById('text1')) {
        text2 = document.getElementById('text1').value
    }
    if (document.getElementById('font1')) {
        font2 = document.getElementById('font1').options[document.getElementById('font1').selectedIndex].text;
    }

    var request = "/ajaxhandler.ashx?requestType=addToCartFromList&nodeId=" + id + "&quantity=" + quantity + "&size=" + size + "&text=" + text + "&font=" + font + "&size2=" + size2 + "&text2=" + text2 + "&font2=" + font2;
    //alert(request);
    callServer(false, request);
    window.setTimeout(refreshSmallBasket, 200);

    /* If the mini-cart is not already flashing then flash it */
    if (flashing == false) {
        flashing = true;
        flashCart();
    }

}

function removeBasketLine(id) {
    callServer(false, '/ajaxhandler.ashx?requestType=removeBasketLine&lineId=' + id);
    window.setTimeout(refreshBasket, 200);
}

function updateBasketLineQuantity(id, ctl) {
    var value = ctl.value;
    callServer(false, '/ajaxhandler.ashx?requestType=adjustBasketLineQuantity&lineId=' + id + '&quantity=' + value);
    window.setTimeout(refreshBasket, 200);
}

function updateMiniCart(response) {
    if (miniCart)
        miniCart.innerHTML = response;
}

function updateCart(response) {

    if (!cartContainer)
        cartContainer = $get('cartContainer');

    if (cartContainer) {
        cartContainer.innerHTML = response;
        //cartContainer.style.overflow = 'scroll';
        initShoppingCart();
    }
}


/*********************************************************
Name:
closeOnEscape script

-----------------------------------------------------------
Description:
Function that hides the shopping cart when the escape key
is pressed

-----------------------------------------------------------
Compatability:
The script is tested compatible with the following browsers:
- Internet Explorer 6
- Internet Explorer 7
- Firefox 2.0.0.3
- Opera 9.10
- Safari 3
- Google Chrome

-----------------------------------------------------------
Dependencies:
none

**********************************************************/

function handleArrowKeys(event) {
    /* Check if the full cart is visible and if not then don't do anything */
    if (cartContainer.className.indexOf('selected') < 0) return;

    var evt = event || window.event;

    if (evt) {
        switch (evt.keyCode) {
            case 27:
                /* Escape key */
                closeCart(); break;
        }
    }
} document.onkeydown = handleArrowKeys;
