// Add site spesific javascript here

var WebShop = Class.create({

    /**
     * Constructor
     *
     * @param unitPriceWebshop
     * @param unitPricePharmacy
     * @param unitPricePortage
     * @param quantumDiscount2
     */
    initialize: function(unitPriceWebshop,unitPricePharmacy,unitPricePortage,fullShipmentPortage,quantumDiscount2) {
        // Add paramteres to the object
        this.unitPriceWebshop = unitPriceWebshop;
        this.unitPricePharmacy = unitPricePharmacy;
        this.unitPricePortage = unitPricePortage;
        this.fullShipmentPortage = fullShipmentPortage;
        this.quantumDiscount2 = quantumDiscount2;

	     // Add observer for each person
	    $R(1,5).each(function(n) {
	        $('person-' + n).observe('click', function() { WebShop.prototype.getInstance().updatePersonCount(n) });
	    });
	    // Add observer on the input box
	    $('persons-total').childElements()[0].observe('change', function() { WebShop.prototype.getInstance().updatePersonCount($('persons-total').childElements()[0].value) });

	    // Add person lines
	    this.updatePersonLines($('persons-total').childElements()[0].value);
    },

    /**
     * Return object instance (singleton)
     *
     * @param unitPriceWebshop
     * @param unitPricePharmacy
     * @param unitPricePortage
     * @param fullShipmentPortage
     * $param quantumDiscount2
     * @return WebShop
     */
    getInstance: function(unitPriceWebshop,unitPricePharmacy,unitPricePortage,fullShipmentPortage, quantumDiscount2) {
        if(!(this.instance instanceof WebShop)) {
            this.instance = new WebShop(unitPriceWebshop,unitPricePharmacy,unitPricePortage,fullShipmentPortage, quantumDiscount2);
        }
        return this.instance;
    },

    /**
     * Function that updates the person count selector
     *
     * @param personCount
     */
	updatePersonCount: function(personCount) {
        // Check min limit
        personCount = personCount < 1 ? 1 : personCount;
        // Check max limit
        personCount = personCount > 5 ? 5 : personCount;

        $('persons-total').childElements()[0].value = personCount;

        // Change active class on the valid person
        $R(1,5).each(function(n) {
            if(n <= personCount) {
                $('person-' + n).addClassName('active');
            } else {
                $('person-' + n).removeClassName('active');
            }
        });

        // Update person quantity
        this.updatePersonLines(personCount);
	},

    /**
     * Function that updates the person lines
     *
     * @param personCount
     */
	updatePersonLines: function(personCount) {
        // Create person lines if not exists
        for(var n=1; n <= personCount; n++) {
            this.createPersonLine(n);
        }

        // Show and hide actual lines
        var elements = $('person-lines').childElements();
        for(var n=1; n <= elements.length; n++) {
            if(n <= personCount) {
                elements[n-1].show();
            } else {
                elements[n-1].hide();
            }
        }

        // Update total quantity
        this.updateTotalQuantity(personCount);
	},

    /**
     * Function that creates a person line
     *
     * @param number
     */
    createPersonLine: function(number) {
        // Create if not exists
        if(!$('person-'+number+'-quantity-1')) {
	        // Line object
	        var objPersonLine = new Element('div', { 'id': 'person-'+number+'-line', 'class': 'person-line'});

	        // Person logo
	        var objPerson = new Element('div', { 'class': 'person-label' });
            objPerson.innerHTML = 'Person ' + number;

	        //Append to person line
	        objPersonLine.appendChild(objPerson);

	        // Quantity pill list
	        var objList = new Element('ul');
	        // Create list elements
	        //$R(1,3).each(function(n) {
	        for(var n=1; n <= 5; n++) {
	            var objListLine = new Element('li', { 'id': 'person-'+number+'-quantity-'+n });
	            if(n == 1) {
	               objListLine.writeAttribute('class','active');
	            }
	            objList.appendChild(objListLine);
	        //});
	        }
	        // Append to person line
	        objPersonLine.appendChild(objList);

	        // Quantity box
	        var objQuantity = new Element('div', { 'id': 'person-'+number+'-quantity-total' });
	        var objQuantityInput = new Element('input', { 'type': 'text', 'name': 'person-'+number+'-quantity', 'value': '1', 'maxlength': '1' });
	        objQuantity.appendChild(objQuantityInput);
	        // Append to person line
	        objPersonLine.appendChild(objQuantity);

	        //Append person line to person container
	        $('person-lines').appendChild(objPersonLine);

            // Add observer for each quantity pills
            $R(1,5).each(function(n) {
                $('person-'+number+'-quantity-'+n).observe('click', function() {
                    WebShop.prototype.getInstance().updatePersonQuantity(number,n);
                });
            });

	        // Add observer for quantity input
            $('person-'+number+'-quantity-total').childElements()[0].observe('change', function() {
                WebShop.prototype.getInstance().updatePersonQuantity(number,$('person-'+number+'-quantity-total').childElements()[0].value);
            });
        }
    },

    /**
     * Function that updates the quantity for each person
     *
     * @param personLine
     * @param quantity
     */
	updatePersonQuantity: function(personLine,quantity) {
        // Check min limit
        quantity = quantity < 1 ? 1 : quantity;
        // Check max limit
        quantity = quantity > 5 ? 5 : quantity;

        $('person-' + personLine + '-quantity-total').childElements()[0].value = quantity;

        // Change active class on the valid person
        $R(1,5).each(function(n) {
            if(n <= quantity) {
                $('person-' + personLine + '-quantity-' + n).addClassName('active');
            } else {
                $('person-' + personLine + '-quantity-' + n).removeClassName('active');
            }
        });

        // Update total quantity
        this.updateTotalQuantity($('persons-total').childElements()[0].value);
	},

    /**
     * Function that updates the total quantity
     *
     * @param personCount Number of selected persons
     */
	updateTotalQuantity: function(personCount) {
	    var count = 0;
        for(var n=1; n <= personCount; n++) {
            count = count + parseInt($('person-' + n + '-quantity-total').childElements()[0].value);
        }
        $('quantity-total').childElements()[0].value = count;

        // Update price
        this.updateTotalPrice(count);
	},

	/**
	 * Function that updates the total price
	 *
	 * @param totalQuantity
	 */
	updateTotalPrice: function(totalQuantity) {
	    var currentFullShipmentPortage = 0;
	    
	   if (this.fullShipmentPortage.include(',')) {
	       tmpArray = this.fullShipmentPortage.split(',');
	       tmpArray.sort();
	       tmpArray.reverse();
	       tmpArray.each(function(item) {
	           dingo=item;
	           if (item.include('=')) {
	               dingo2=item;
	               qntyClass = item.split('=',2);
	               if (!IsNumeric(qntyClass[0]) || !IsNumeric(qntyClass[1]) ) {
	                   alert('fullShipmentPortage not properly defined');
	                   throw $break;
	               }
	               
	               if (totalQuantity >= qntyClass[0]) {
	                   currentFullShipmentPortage = qntyClass[1] / 3;
	                   throw $break;
	               }
	               
	           } else {
	               alert('fullShipmentPortage not properly defined');
	           }
	         });
	   }
	   
       $('price-webshop').innerHTML = (totalQuantity > 1) ? (totalQuantity * (this.unitPriceWebshop - this.quantumDiscount2)) : (totalQuantity * this.unitPriceWebshop);
       $('price-pharmacy').innerHTML = totalQuantity * this.unitPricePharmacy;
       total = (totalQuantity > 1) ? (totalQuantity * (this.unitPriceWebshop + this.unitPricePortage - this.quantumDiscount2) + currentFullShipmentPortage) : (totalQuantity * (this.unitPriceWebshop + this.unitPricePortage) + currentFullShipmentPortage);
       $('price-total').innerHTML = Math.round(total);
	}
});

function IsNumeric(input)
{
    return (input - 0) == input && input.length > 0;
}

function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

function changearticle(artId,i){
$$(".shownone").each(function(article) {
	article.hide();
});
$("shadow-container").removeClassName("shadow0");
$("shadow-container").removeClassName("shadow1");
$("shadow-container").removeClassName("shadow2");
$("shadow-container").removeClassName("shadow3");
$("shadow-container").removeClassName("shadow4");
$("shadow-container").addClassName("shadow"+i);


$('art'+artId).show();
$$(".imgactive").each(function(imgact) {
	imgact.removeClassName("imgactive");
});
$('img'+artId).addClassName("imgactive");
}


/* Campaign switcher frontpage */

var currentCampaign = 0;
var campaignTimer = 0;

function campaignChangeTo(i) {

    $$('.campaign-articlelist .list-navigation .pages').each(function(link){
        link.down().src = '/themes/medox/images/circle-off.png';
    }.bind(this));

    $$('.campaign-articlelist li').each(function(campaign){
        if (campaign.id == 'campaign-item'+i) {
            $('campaignLink'+i).down().src = '/themes/medox/images/circle-on.png';
            campaign.appear({duration: 1.0});
        } else {
            campaign.fade({duration: 0.8});
        }
    }.bind(this));

    currentCampaign = i;
}

var campaignCount;

function loopCampaigns() {
    campaignChangeTo((currentCampaign + 1) % campaignCount);
}



function nextBanner() {
    if(currentCampaign < (campaignCount-1)) {
        currentCampaign++;
    } else if (currentCampaign == (campaignCount-1)) {
       currentCampaign = 0;
    }
    campaignChangeTo(currentCampaign);
}

function prevBanner() {
    if(currentCampaign > 0) {
        currentCampaign--;
    } else if (currentCampaign == 0) {
       currentCampaign = (campaignCount-1);
    }
    campaignChangeTo(currentCampaign);
}



