
var DEBUG_PERSIST = false;

var SHOPPING_CART;

addEvent(window, "load", initShoppingCart);
addEvent(window, "unload", persistShoppingCart);

function ShoppingCartItem(id, name, price) {
    // fields
    this.id = id;
    this.name = name;
    this.price = price;
    this.amount = 1;
    this.cart = null;

    // public mehtods
    this.toJSON = toJSON;
    this.incAmount = incAmount;
    this.decAmount = decAmount;
    this.setAmount = setAmount;
    this.setShoppingCart = setShoppingCart;
    this.getPrice = getPrice;
    this.getDisplayPrice = getDisplayPrice;

    function incAmount() {
        this.amount += 1;
    }

    function decAmount() {
        this.amount -= 1;
    }

    function setAmount( amount ) {
        this.amount = amount;
    }

    function toJSON() {
        var retval = "\t{\n";
        retval += "\t\tid\t:\t'" +  this.id + "',\n";
        retval += "\t\tname\t:\t'" +  this.name.replace(/'/g, "\\'" ) + "',\n";
        retval += "\t\tprice\t:\t" +  this.price + ",\n";
        retval += "\t\tamount\t:\t" +  this.amount + "\n";
        retval += "\t}\n";

        return retval;
    }

    function setShoppingCart( cart ) {
        this.cart = cart;
    }

    function getPrice() {
        return this.price * this.amount;
    }

    function getDisplayPrice() {
        var price = ""+this.getPrice();
        while ( price.length < 3 ) {
            price = "0" + price;
        }

        return price.substring(0, price.length - 2 ) + "," + price.substring( price.length - 2, price.length );
    }

}

function ShoppingCart() {
    // fields
    this.items = new Array();

    // public methods:
    this.addItem = addItem;
    this.removeItem = removeItem;
    this.removeItemWithId = removeItemWithId;
    this.getTotalPrice = getTotalPrice;
    this.getTotalDisplayPrice = getTotalDisplayPrice;
    this.createBuyLink = createBuyLink;
    this.clear = clear;

    this.getItems = getItems;
    this.toJSON = toJSON;
    this.isEmpty = isEmpty;

    this.persist = persist;
    this.load = load;

    this.incAmountOfItem = incAmountOfItem;
    this.decAmountOfItem = decAmountOfItem;

    this.getFromBackend = getFromBackend;

    init(this);

    // constructor:
    function init( self ) {
        if (  navigator.cookieEnabled != false && self.items.length == 0 && document.cookie ) {
            var value = "";
        
            try {
    
                var results = document.cookie.match ('shoppingcart=(.*?)(;|$)' );

                if ( results )
                    value = unescape ( results[1] );
                else
                    return;

                if ( DEBUG_PERSIST ) {
                    alert( "loading:\n" + value );
                }

                var root = eval( value );

                for ( var i = 0; i < root.length; i++ ) {
                    var item = root[i];
                    
                    var newScItem = new ShoppingCartItem( item.id, item.name, item.price );
                    newScItem.setAmount( item.amount );

                    self.addItem( newScItem );
                }
            } catch(err) {
                alert("Couldn't parse state: " + value );
            }
        }
    }

    function load() {
        init( this );
    }

    function clear() {
        this.items = new Array();
        this.persist(); 
   }

    function addItem( item ) {
        for ( var i = 0; i < this.items.length; i++ ) {
            var existingItem = this.items[i];
            if ( existingItem.id == item.id ) {
                existingItem.incAmount();
                return;
            }
        }

        item.setShoppingCart( this );
        this.items.push( item );
    }

    function removeItem( item ) {
            this.removeItemWithId( item.id ); 
     }

    function removeItemWithId( id ) {
        if ( this.items.length > 0 ) {
                    var newCart = new Array();
                    var oldItem = this.items.shift();
        
                    while ( oldItem ) {
                        if ( oldItem.id != id ) {
                        
                            newCart.push( oldItem );
                        } else {
                            if ( oldItem.amount > 1 ) {
                                oldItem.decAmount();
                                newCart.push( oldItem );
                            }
                        }


                        if ( this.items.length > 0 ) {
                            oldItem = this.items.shift();
                        } else {
                            oldItem = null;
                        }
                    }

                    this.items = newCart;
                }
    }

    function incAmountOfItem( id ) {
        for ( var i = 0; i < this.items.length; i++ ) {
            var existingItem = this.items[i];
            if ( existingItem.id == id ) {
                existingItem.incAmount();
                return;
            }
        }
    }

    function decAmountOfItem( id ) {
        for ( var i = 0; i < this.items.length; i++ ) {
            var existingItem = this.items[i];
            if ( existingItem.id == id ) {
                existingItem.decAmount();
                return;
            }
        }
    }

    function getTotalPrice() {
        var totalPrice = 0;

        for ( var i = 0; i < this.items.length; i++ ) {
            totalPrice += this.items[i].price * this.items[i].amount;
        }

        return totalPrice;
    }

    function getTotalDisplayPrice() {
        var price = ""+this.getTotalPrice();
        while ( price.length < 3 ) {
            price = "0" + price;
        }

        return price.substring(0, price.length - 2 ) + "," + price.substring( price.length - 2, price.length );
    }


    function toJSON() {
        var retval = " {\n";
        retval += "\titems\t:\t[\n";
        
        for ( var i = 0; i < this.items.length; i++ ) {
            retval += this.items[i].toJSON();
            if ( i < this.items.length - 1 ) {
                retval += ",\n";
            }
        }

        retval += "\t]\n";
        retval += "};";

        return retval;
    }


    function persist() {
        if ( navigator.cookieEnabled != false ) {
            document.cookie = "shoppingcart=" + escape( this.toJSON().replace(/\n+/g,"") ) + ";";
            if ( DEBUG_PERSIST ) {
                alert( "Stored (document.cookie):\n" + document.cookie );
            }
        }
    }

    function getItems() {
        return this.items;
    }

    function isEmpty() {
        return this.items.length == 0;
    }

    function getFromBackend() {
        //alert("Shopping cart Would load from backend");

    }

}

function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    // wer auch immer die untere Zeile hat einkommentiert gelassen, sollte darber nochmal nachdenken...
    // alert("Handler could not be added");
  }
}

function removeEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.removeEventListener){
    elm.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.detachEvent){
    var r = elm.detachEvent("on"+evType, fn);
    return r;
  } else {
    // wer auch immer die untere Zeile hat einkommentiert gelassen, sollte darber nochmal nachdenken...
    // alert("Handler could not be removed");
  }
}

function initShoppingCart() {
    SHOPPING_CART = new ShoppingCart();
    SHOPPING_CART.load();
    showCart( SHOPPING_CART );

    SYSTEM_MESSAGE_BUS.register( SM_USER_LOGIN, SHOPPING_CART.getFromBackend );
}

function persistShoppingCart() {
    SHOPPING_CART.persist();
}

function showCart( sc ) {
    var scHTML = "";
    if ( !sc.isEmpty() ) {
    
        scHTML += "<div id=\"warenkorb\">";
		scHTML += "<div class=\"headlineBox\"><table><tr><td><img src=\"./img/ico_warenkorb_weiss.gif\"/></td><td><h2>Ihr Warenkorb</h2></td></tr></table></div>";
		scHTML += "<div class=\"elements\">";
        var items = sc.getItems();
    	
        for ( var i = 0; i < items.length; i++ ) {
				if (i%2 == 0) {
					scHTML += "<div class=\"warenkorb_element hell\">";
				}
				else {
					scHTML += "<div class=\"warenkorb_element dunkel\">";
				}
				
				scHTML += "<table><tr>";
				scHTML += "<td class=\"menge\"><b> " + items[i].amount + "</b></td>";
				scHTML += "<td class=\"mal\"> x </td>";
				scHTML += "<td class=\"warenkorb_element_titel\">" + items[i].name.substring(0,15) + "...<br/>";
				scHTML += "<div class=\"mehrWenigerButton\">";
				scHTML += "<a onclick=\"javascript:incAmountId('" + items[i].id + "');\" title=\"ein Artikel mehr\"><img src=\"./img/plusInaktiv.gif\" id=\"plusImage_"+i+"\" onmouseover=\"swapImage('plusImage_"+i+"',1);\" onmouseout=\"swapImage('plusImage_"+i+"',2);\"\></a>";
				scHTML += "<a onclick=\"javascript:removeId('" + items[i].id + "');\" title=\"ein Artikel weniger\"><img src=\"./img/minusInaktiv.gif\" id=\"minusImage_"+i+"\" onmouseover=\"swapImage('minusImage_"+i+"',3);\" onmouseout=\"swapImage('minusImage_"+i+"',4);\"></a>";
				scHTML += "</div></td>";
				scHTML += "<td class=\"warenkorb_element_preis\"><span>CHF "  + items[i].getDisplayPrice() + "</span></td>";
				scHTML += "</tr></table>";
				scHTML += "</div>";
    
        }
		scHTML += "<div class=\"clear\"></div></div>";
    
		  	scHTML += "<div class=\"warenkorb_total\">";
			scHTML += "<table><tr>"
			scHTML += "<td class=\"checkout\">" + sc.createBuyLink() + "</td>";
			scHTML += "<td class=\"total_price\">CHF " +  sc.getTotalDisplayPrice()  + "</td>";
			scHTML += "</tr></table>";
			scHTML += "</div>"; 

    }

    document.getElementById("sc").innerHTML = scHTML;
}


function swapImage(sender, icon){
	if(icon == 1){
		document.getElementById(sender).src = "./img/plusAktiv.gif";		
	}
	if(icon == 2){
		document.getElementById(sender).src = "./img/plusInaktiv.gif";		
	}
	if(icon == 3){
		document.getElementById(sender).src = "./img/minusAktiv.gif";		
	}
	if(icon == 4){
		document.getElementById(sender).src = "./img/minusInaktiv.gif";		
	}	 
}

function createBuyLink() {
    return '<a onclick="buyShoppingCart();" href="#">zur Kasse</a>&nbsp;&raquo;';

}


  function addToCart( id, name, price) {
		addToCartClose( id, name, price );
            }

  function addToCartClose( id, name, price) {
                var item1 = new ShoppingCartItem( id, name, price );
                    
                SHOPPING_CART.addItem( item1 );
                
                showCart( SHOPPING_CART );                
   Element.remove($('lbContent'));
    if (browser == "Internet Explorer"){

            window.scrollTo(0, 0);

            bod = document.getElementsByTagName('body')[0];
	    bod.style.height = "auto";
	    bod.style.overflow = "auto";
  
	    htm = document.getElementsByTagName('html')[0];
	    htm.style.height = "auto";
	    htm.style.overflow = "auto"; 

           selects = document.getElementsByTagName('select');
	   for(i = 0; i < selects.length; i++) {
	       selects[i].style.visibility = "visible";
	   }

    }

    $('overlay').style.display = "none";
    $('lightbox').style.display = "none";
            }

    function removeId( id ) {
        SHOPPING_CART.removeItemWithId( id );
        showCart( SHOPPING_CART );
    }
    
    function incAmountId( id ) {
        SHOPPING_CART.incAmountOfItem( id );
        showCart( SHOPPING_CART );
    }

function buyShoppingCart() {
    var items = SHOPPING_CART.getItems();
    var checkout = 'http://www.books.ch/shop/action/shoppingcart/add?'
        for ( var i = 0; i < items.length; i++ ) {
            var item = items[i];
		    checkout += 'artiId=' + item.id;
		    checkout += '&amount=' + item.amount;
	    
		    if ( i + 1 < items.length ) {
			checkout += '&';
		    }
        }
		checkout += "&action=cart&adCode=132Q00O42V11A";
    
    window.open(  checkout, 'checkout' );
    //console.log("checkoutLink = " +checkout);

    SHOPPING_CART.clear();

    showCart( SHOPPING_CART );
}

