﻿/* --------------------------------------------- */
/*     Shop Delegate                                */
/* --------------------------------------------- */
var STOCKCOUNT_NOTAVAILABLE = 1;
var STOCKCOUNT_FEWAVAILABLE = 6;
var ARTICLE_PRICE_FORMATER_MINSAVE = 20;
var SERVICE_URI = 'http://www.olympus.de/consumer/store/ecommerce/control/';
function ShopDelegate() {
    if (typeof ShopDelegate._initialized == "undefined") {
        ShopDelegate.prototype.loadUserStatus = function(serviceResponder) {
             if (ShopDelegate.enabled) new Ajax.Request(SERVICE_URI + 'getBasketInfo', 
                {
                    evalScripts:true, method:'get', requestHeaders:['Cache-Control','no-cache'],
                    onSuccess: function(response) {
                        try { loggedIn = response.responseXML.documentElement.getElementsByTagName('loggedin')[0].firstChild.data == "Y" } catch (e) { loggedIn = false; }
                        serviceResponder.onSuccess({ 
                            loggedIn : loggedIn
                        });
                    },
                    onFailure: function(response) {
                        //console.log(response.status);
                        serviceResponder.onFailure();
                    }
                } 
            );
        }        
        ShopDelegate.prototype.loadArticleShopData = function(serviceResponder, id) { 
            if (ShopDelegate.enabled) new Ajax.Request(SERVICE_URI + 'getArticleInfo?article_no=' + id, 
                {
                    evalScripts:false, method:'get', requestHeaders:['Cache-Control','no-cache'],
                    onSuccess: function(response) {
                        //console.log("ShopDelegate.getArticleInfo() - response.responseText: " + response.responseText);
                        try { price = response.responseXML.documentElement.getElementsByTagName('price')[0].firstChild.data } catch (e) { price = null; }
                        try { currency = response.responseXML.documentElement.getElementsByTagName('currency')[0].firstChild.data } catch (e) { currency = null; }
                        try { stock = response.responseXML.documentElement.getElementsByTagName('stock')[0].firstChild.data } catch (e) { stock = null; }
                        try { discontinued = (response.responseXML.documentElement.getElementsByTagName('discontinued')[0].firstChild.data == "Y") } catch (e) { discontinued = false; }
                        (price==null) ? priceObject = null : priceObject = new Price(price, currency);
                        serviceResponder.onSuccess({
                            price : priceObject,
                            stock : stock,
                            discontinued : discontinued 
                        });
                    },
                    onFailure: function(response) {
                        //console.log(response.status);
                        serviceResponder.onFailure();
                    }
                }
            );
        }
        ShopDelegate.prototype.loadWishlistStatus = function(serviceResponder) { 
            if (ShopDelegate.enabled) new Ajax.Request(SERVICE_URI + 'getBasketInfo', 
                {
                    evalScripts:false, method:'get', requestHeaders:['Cache-Control','no-cache'],
                    onSuccess: function(response) {
                        //console.log("ShopDelegate.loadWishlistStatus() - response.responseText: " + response.responseText);
                        try { articleCount = Math.round(response.responseXML.documentElement.getElementsByTagName('wishlistsum')[0].firstChild.data) } catch (e) { articleCount = 0; }
                        serviceResponder.onSuccess({
                            articleCount : articleCount
                        });
                    },
                    onFailure: function(response) {
                        //console.log(response.status);
                        serviceResponder.onFailure();
                    }
                }
            );
        }
        ShopDelegate.prototype.loadShoppingCartStatus = function(serviceResponder) { 
             if (ShopDelegate.enabled) new Ajax.Request(SERVICE_URI + 'getBasketInfo', 
                {
                    evalScripts:false, method:'get', requestHeaders:['Cache-Control','no-cache'],
                    onSuccess: function(response) {
                        //console.log("ShopDelegate.loadShoppingCartStatus() - response.responseText: " + response.responseText);
                        try { count = Math.round(response.responseXML.documentElement.getElementsByTagName('articlesum')[0].firstChild.data) } catch (e) { count = 0; }
                        try { total = new Price(response.responseXML.documentElement.getElementsByTagName('basketsum')[0].firstChild.data,"EUR"); } catch (e) { total = new Price(0,"EUR"); }
                        serviceResponder.onSuccess({
                            count : count,
                            total : total,
                            delivery : 'Standardversand: € 5,00'  //Standardversand: € 5,00
                        });
                    },
                    onFailure: function(response) {
                        //console.log(response.status);
                        serviceResponder.onFailure();
                    }                
                }
            );
        }
        ShopDelegate._initialized = true;
        ShopDelegate.enabled = ("" == "");
    }
}
/* --------------------------------------------- */
/*     Action Definitions                           */
/* --------------------------------------------- */
function LoadUserStatusAction() {
    if (typeof LoadUserStatusAction._initialized == "undefined") {
        LoadUserStatusAction.prototype.execute = function(event) {
            this.viewHelper = event.data;
            (new ShopDelegate()).loadUserStatus(this);
        }
        LoadUserStatusAction.prototype.onSuccess = function(data) {
            this.viewHelper.setLoggedIn(data.loggedIn);
            this.viewHelper.setInfoDisplay(false);         
        }
        LoadUserStatusAction.prototype.onFailure = function() {
            this.viewHelper.setInfoDisplay(true); 
        }
        LoadUserStatusAction._initialized = true;
    }
}
function LoadArticleDataAction() {
    if (typeof LoadArticleDataAction._initialized == "undefined") {
        LoadArticleDataAction.prototype.execute = function(event) {
            this.viewHelper = event.data;
            (new ShopDelegate()).loadArticleShopData(this,this.viewHelper.getArticleId());
        }
        LoadArticleDataAction.prototype.onSuccess = function(data) {
            if (data.discontinued) {
                this.viewHelper.setButtonWishDisplay(false);
                this.viewHelper.setPriceInfo(articlePriceFormater.formatEuro(this.viewHelper.getPriceOld()));
            } else {
                if (data.price != null) {
                    if (articlePriceFormater.isPriceAdvantage(this.viewHelper.getPriceOld(), data.price)) {
                        this.viewHelper.setPriceDescription(articlePriceFormater.formatDiff(this.viewHelper.getPriceOld(), data.price));
                        if (this.viewHelper.getPriceOld().value > data.price.value) this.viewHelper.setPriceInfo(this.viewHelper.getPriceOld());
                        if (this.viewHelper.getPriceOld().value > data.price.value) this.viewHelper.setPriceInfoStriked();
                    } else {
                        this.viewHelper.setPriceInfo("UVP"); // UVP
                    }
                    this.viewHelper.setPriceDescription(articlePriceFormater.formatDiff(this.viewHelper.getPriceOld(), data.price)); 
                    this.viewHelper.setPriceField(data.price);
                    this.viewHelper.setAvailability(availabilityFormater.format(data.stock));
                    this.viewHelper.setAvailabilityStyle(availabilityFormater.getClassName(data.stock));
                    this.viewHelper.setButtonWishDisplay(true);
                    this.viewHelper.setButtonBuyDisplay(data.stock > STOCKCOUNT_NOTAVAILABLE);
                    this.viewHelper.setButtonReserveDisplay(data.stock <= STOCKCOUNT_NOTAVAILABLE);
                }
                else {
                    // Artikel in ShopDB nicht vorhanden
                    this.viewHelper.setAvailabilityStyle("notavailable");
                    this.viewHelper.setAvailability(" ");
                    this.viewHelper.setBackground("#fff");
                    if (this.viewHelper.getPriceOld().value != undefined) { this.viewHelper.setPriceInfo("UVP"); } 
                }
            }
        }
        LoadArticleDataAction.prototype.onFailure = function() {
            // Shop nicht erreichbar
            this.viewHelper.setAvailabilityStyle("notavailable");
            this.viewHelper.setAvailability(" ");
            if (this.viewHelper.getPriceOld().value != undefined) { this.viewHelper.setPriceInfo("UVP"); } 
        }
        LoadArticleDataAction._initialized = true;
    }
}
function LoadWishlistStatusAction() {
    if (typeof LoadWishlistStatusAction._initialized == "undefined") {
        LoadWishlistStatusAction.prototype.execute = function(event) {
            this.viewHelper = event.data;
            (new ShopDelegate()).loadWishlistStatus(this);
        }
        LoadWishlistStatusAction.prototype.onSuccess = function(data) {
            this.viewHelper.setArticleCount(data.articleCount);
            this.viewHelper.setDisplay((data.articleCount != 0)); // Ausblenden wenn kein Artikel in Merkliste
        }
        LoadWishlistStatusAction.prototype.onFailure = function() {
            this.viewHelper.setDisplay(false); // Modul Ausblenden wenn Shop nicht erreichbar
        }
        LoadWishlistStatusAction._initialized = true;
    }    
}
function LoadShoppingCartStatusAction() {
    if (typeof LoadShoppingCartStatusAction._initialized == "undefined") {
        LoadShoppingCartStatusAction.prototype.execute = function(event) {
            this.viewHelper = event.data;
            (new ShopDelegate()).loadShoppingCartStatus(this);
        }
        LoadShoppingCartStatusAction.prototype.onSuccess = function(data) {
            this.viewHelper.setCount(data.count);
            this.viewHelper.setPrice(data.total);
            this.viewHelper.setPriceDisplay((data.count != 0));
            this.viewHelper.setInfo(data.delivery);
            this.viewHelper.setInfoDisplay(true);                
            this.viewHelper.setOrderButtonDisplay((data.count != 0));
        }
        LoadShoppingCartStatusAction.prototype.onFailure = function() {
            this.viewHelper.setInfo("Der Online-Shop steht aus technischen Gründen zur Zeit nicht zur Verfügung."); // Alternativtext wenn Shop nicht erreichbar
            this.viewHelper.setInfoDisplay(true);    
        }
        LoadShoppingCartStatusAction._initialized = true;
    }    
}
function AddToCartAction() {
    if (typeof AddToCartAction._initialized == "undefined") {
        AddToCartAction.prototype.execute = function(event) {
            var submit = document.createElement("input");
            submit.type = "submit";
            var input1 = document.createElement("input");
            input1.name="add_product_id";
            input1.value=event.data.articleID;
            var input2 = document.createElement("input");
            input2.name="quantity";
            input2.value=1;
            var input3 = document.createElement("input");
            input3.name="URL";
            input3.value= event.data.successURL;
            var form  = document.createElement("form");
            form.style.display='none';
            form.action = SERVICE_URI + "additem";
            form.method="POST";
            form.appendChild(submit);
            form.appendChild(input1);
            form.appendChild(input2);
            form.appendChild(input3);
            document.body.appendChild(form);
            form.submit();
        }
        AddToCartAction._initialized = true;
    }    
}
function AddToWishlistAction() {
    if (typeof AddToWishlistAction._initialized == "undefined") {
        AddToWishlistAction.prototype.execute = function(event) {
            var submit = document.createElement("input");
            submit.type = "submit";
            var input1 = document.createElement("input");
            input1.name="product_id";
            input1.value=event.data.articleID;
            var input2 = document.createElement("input");
            input2.name="quantity";
            input2.value=1;
            var input3 = document.createElement("input");
            input3.name="URL";
            input3.value= document.URL;
            var form  = document.createElement("form");
            form.style.display='none';
            form.action = SERVICE_URI + "addItemToShoppingList";
            form.method="POST";
            form.appendChild(submit);
            form.appendChild(input1);
            form.appendChild(input2);
            form.appendChild(input3);
            document.body.appendChild(form);
            form.submit();
        }
        AddToWishlistAction._initialized = true;
    }    
}
function ReserveAction() {
    if (typeof ReserveAction._initialized == "undefined") {
        ReserveAction.prototype.execute = function(event) {
            //console.log("test");
            var submit = document.createElement("input");
            submit.type = "submit";
            var input1 = document.createElement("input");
            input1.name="add_product_id";
            input1.value=event.data.articleID;
            var input2 = document.createElement("input");
            input2.name="quantity";
            input2.value=1;
            var input3 = document.createElement("input");
            input3.name="URL";
            input3.value= event.data.successURL;
            var form  = document.createElement("form");
            form.style.display='none';
            form.action = SERVICE_URI + "additem";
            form.method = "POST";
            form.appendChild(submit);
            form.appendChild(input1);
            form.appendChild(input2);
            form.appendChild(input3);
            document.body.appendChild(form);
            form.submit();
        }
        ReserveAction._initialized = true;
    }    
}

/* --------------------------------------------- */
/*     Formatters                                   */
/* --------------------------------------------- */
availabilityFormater = {
    format : function(value) {
        if ( value <= STOCKCOUNT_NOTAVAILABLE ) return "Vorübergehend nicht verfügbar";  //Nicht lieferbar
        if ( value <= STOCKCOUNT_FEWAVAILABLE ) return "Nur wenige lieferbar"; //Nur wenige lieferbar
        return "Lieferbar";
    },
    getClassName : function(value) {
        if ( value <= STOCKCOUNT_NOTAVAILABLE ) return "notavailable";
        if ( value <= STOCKCOUNT_FEWAVAILABLE ) return "fewavailable";
        return "available";
    }
};
articleCountFormater =  {
    format : function(value) {
        return (value <= 0) ? "0 Artikel" : value + " Artikel"; //Artikel
    }
};
articlePriceFormater =  {
    formatDiff : function(priceOld, price) {
        return (this.isPriceAdvantage(priceOld, price)) ? "Sie sparen " + priceDif : "";  //Sie sparen
    },
    isPriceAdvantage : function(priceOld, price) {
        priceDif = priceOld.sub(price);
        return (priceDif.value >= ARTICLE_PRICE_FORMATER_MINSAVE);
    }
};
function Price(str, currency) {
    var value;
    var currency;
    if (typeof Price._initialized == "undefined") {
        Price.prototype.parseValue = function(str) {
            str = str.replace(/ /g,"");
            if (str.indexOf("&euro") > -1) return Number(str.replace(/&euro/g,"").replace(/\./g,"").replace(/,/g,"."));
            if (str.indexOf("€") > -1) return Number(str.replace(/€/g,"").replace(/\./g,"").replace(/,/g,"."));
            return undefined;
        }
        Price.prototype.parseCurrency = function(str) {
            str = str.replace(/ /g,"");
            if (str.indexOf("&euro") > -1) return "EUR";
            if (str.indexOf("€") > -1) return "EUR";
            return undefined;
        }
        Price.prototype.add = function(otherPrice) {
            if (this.currency == otherPrice.currency) return new Price(this.value + otherPrice.value, this.currency);
            return "Can't add " + this.currency + " to " + otherPrice.currency;
        }
        Price.prototype.sub = function(otherPrice) {
            if (this.currency == otherPrice.currency) return new Price(this.value - otherPrice.value, this.currency);
            return "Can't sub " + otherPrice.currency + " from " + this.currency;
        }
        Price.prototype.toString = function() { 
            if (this.currency == "EUR") { 
                var str = (new String(Math.round(this.value*100)/100)).replace(".",",");
                switch ((str.indexOf(',')== -1) ? 0: str.substr(str.indexOf(',')).length) {
                    case 0 : 
                        return "&euro; " + str + ",00" 
                        break
                    case 1 :
                        return "&euro; " + str + "00"
                        break
                    case 2 :
                        return "&euro; " + str + "0"
                        break
                    case 3 :
                        return "&euro; " + str
                        break
                }
            } else {
                return  this.currency + " " +  this.value;
            }        
        }
        Price._initialized = true;
    }
    if (typeof(currency) == "undefined" || currency == "undefined") {
        this.value = Price.prototype.parseValue(str);
        this.currency = Price.prototype.parseCurrency(str);
    } else {
        this.value = Number(str);
        this.currency = currency;
    }
    //console.log("new Price (" +str + "," + currency + ") > " + this.toString() );
}

/* --------------------------------------------- */
/*     View Controller                             */
/* --------------------------------------------- */
function ViewController() {
    var views = Array();
    var _initialized;
    if (typeof ViewController._initialized == "undefined") {
        ViewController.prototype.getView = function (viewName) { 
            return (views.find(function(s) {  return s.name == viewName; })).view;
        }
        ViewController.prototype.registerView = function ( viewName, view ) { 
            //console.log("ViewController.registerView()", viewName, view);
            views.push( { name:viewName, view:view } ) ;
        }
        ViewController._initialized = true;
    }    
}
var viewController = new ViewController();

/* --------------------------------------------- */
/*     Event Controller                             */
/* --------------------------------------------- */
function EventController() {
    var actions = Array();
    var _initialized;
    if (typeof EventController._initialized == "undefined") {
        EventController.prototype.handleEvent = function (event) { 
            for (i=0; i<actions.length; i++)  
                if (actions[i].eventName == event.name) {
                    //console.log("EventController.handleEvent() - " + event.name);
                    eval("new " + actions[i].action + "();").execute( event );
                }
        }
        EventController.prototype.registerAction = function ( eventName, action ) { 
            actions.push( {eventName:eventName, action:action } ) ;
        }
        EventController._initialized = true;
    }    
}
var eventController = new EventController();
eventController.registerAction( 'loadArticleData', 'LoadArticleDataAction' );
eventController.registerAction( 'loadWishlistStatus', 'LoadWishlistStatusAction' );
eventController.registerAction( 'loadShoppingcartStatus', 'LoadShoppingCartStatusAction' );
eventController.registerAction( 'loadUserStatus', 'LoadUserStatusAction' );
eventController.registerAction( 'addToCart', 'AddToCartAction' );
eventController.registerAction( 'addToWishlist', 'AddToWishlistAction' );
eventController.registerAction( 'reserve', 'ReserveAction' );
