/**
 * file default.js
 *
 * contains javascript for Van Gansewinkel website
 *
 * @require MooTools version 1.2.4 core & more
 *
 */

var sBasketContentsPanelRefreshButtonClientId = null;
var sBasketContentsPanelDeleteButtonClientId = null;
var sBasketContentsPanelDeleteCommandClientId = null;
var sOrderPanelRefreshButtonClientId = null;
var sPropositionPanelRefreshButtonClientId = null;

var sProductIsToegevoegdAanOfferte = "";
var sProductIsToegevoegdAanWinkelwagen = "";
var sErIsEenFoutOpgetreden = "";
var sOfferteIsBijgewerkt = "";
var sWinkelwagenIsBijgewerkt = "";
var sWiltUDitProductVerwijderen = "";

window.addEvents({
    'domready': function() {
        initDatePicker();
        initFAQ();
        preventCheckboxBubbling();
        initNumberControllers();
    },
    'load': function() {
        initEndRequestHandler();
        initShopNotification();
        initOrderButtons();
        
        equalizeHeight(document.getElements('ul.lang_selection li div'));
        equalizeHeight(document.getElements('ul.lang_selection li div p.public'));
        
    }
});

/**
* initEndRequestHandler, required for AJAX client-server communication, function 'endRequestHandler' is called after AJAX request has ended
*
* @author Dennis Velthuis <dennis.velthuis[AT]efocus.nl>
* @since 1.0, 14 jan 2010
* @return void
*/
function initEndRequestHandler() {
    if (typeof (test) != 'undefined') Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}

/**
 * initDatePicker
 *
 * @author Klaas Dieleman <klaas[AT]efocus.nl>
 * @author Mirjam <mirjam[AT]efocus.nl>
 * @since 1.2, 10 may 2010
 * @return void
 */
 
function initDatePicker() {
	if (document.getElement('input.date')) {
		var objToday = new Date();
		var strToday = objToday.getFullYear().toString() + '-' + (objToday.getMonth() + 1).toString() + '-' +  objToday.getDate().toString();
		
		var objTomorrow = new Date();
		var strTomorrow = objTomorrow.getFullYear().toString() + '-' + (objTomorrow.getMonth() + 1).toString() + '-' +  (objTomorrow.getDate() + 1).toString();
		
		new efDatePicker('input.date', {
			pickerClass			: 'datepicker_vista',
			inputOutputFormat	: 'd-m-Y',
			allowEmpty			: true,
			positionOffset		: { x: -30, y: 0 },
			days				: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
			months				: ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
			disallowedDates		: { dates: holidays, inputFormat: 'd-m-Y' },
			disallowedWeekdays	: [0, 6],
			minDate				: { date: strTomorrow, inputFormat: 'Y-n-d' }
		});
	};
}

/**
 * initFAQ
 *
 * @author Mirjam <mirjam[AT]efocus.nl>
 * @since 1.0, 05 jan 2010
 * @return void
 */

function initFAQ() {

    var list = $(document.body).getElement('div.faq dl');
    if (!list) return;

    var handles = list.getElements('dt');
    var answers = list.getElements('dd');

    var faqAccordion = new Fx.Accordion(handles, answers, {
        'onActive': function(toggler, element) {
            toggler.addClass('open');
        },
        'onBackground': function(toggler, element) {
            toggler.removeClass('open');
        },
        'alwaysHide': true,
        'show': 0
    });
   
}

/**
 * prevents bubbling of click event to checkbox when clicking on link inside the same label
 *
 * @author Klaas <klaas[AT]efocus.nl>
 * @since 1.0, 06 jan 2010
 * @return void
 */

function preventCheckboxBubbling() {
	var checkboxLabels = $$('label').filter(function(cbLabel) {
		if(cbLabel.getElement('input[type=checkbox') && cbLabel.getElement('a')) return cbLabel;
	});
	
	checkboxLabels.each(function(cbLabel) {
		cbLabel.getElements('a').each(function(linkElement) {
			linkElement.addEvent('click', function(event) {
				event.stop();
				var targetFrame = (linkElement.get('target') || '_self');
				window.open(linkElement.get('href'), targetFrame);
			});
		});
	});
}

/**
 * attaches plus/min buttons to amount-inputs
 *
 * @author Klaas <klaas[AT]efocus.nl>
 * @since 1.0, 12 jan 2010
 * @return void
 */

function initNumberControllers() {
    var numberInputs = document.getElements('input.numbercontrol');
	new numberControl(numberInputs, {
	    'minValue': 1,
	    'allowEmpty': false,
	    'onChange': function(el) {
	        if (!el.isValid) {
	            el.addClass('error');
	        } else {
	            el.removeClass('error');
	            this.disableButtons();
	            RefreshBasket(sBasketContentsPanelRefreshButtonClientId);
	        }
	    }
	});
}

/**
* initializes notification, uses notification class
*
* @author Mirjam <mirjam[AT]efocus.nl>
* @since 1.0, 11 jan 2010
*
* @return void
*/

var thisNotification;
function initShopNotification() {
	var fadeTime;
	Browser.Engine.trident ? fadeTime = 0 : fadeTime = 0.5;
    thisNotification  = new notification({'position': 'center', 'duration': 1.5, 'fadetime': fadeTime});

}

/**
* shows notification
*
* @author Mirjam <mirjam[AT]efocus.nl>
* @since 1.0, 11 jan 2010
*
* @param sender, button or link that calls the function
* @param options, specific options for this notification
*
* @return void
*/

function showShopNotification(sender, options) {

    thisNotification.show(sender, options);
    
}

/**
* an onchange submits form to self, adds id and other to url
*
* @param id, value of form element 
* @param extras, additional params
* 
* @author Mirjam <mirjam{AT}efocus.nl>
* @since 1.0, 13 nov 2009
* @return void
*/

function onChangeForm(extras) {

    var qString = '';

    if (extras) {
        qString += extras;
    }

    window.location = qString;

}

/**
* initializes functionality of orderbuttons
* 
* @author Klaas Dieleman <klaas{AT}efocus.nl>
* @since 1.0, 13 jan 2010
* @return void
*/
function initOrderButtons() {
	$$('fieldset.orderproduct').each(function(el) {
	    var strProductId = el.getElement('input[name="productId"]').get('value');
	    var strQuantity = el.getElement('input[name="quantity"]').get('value');
	    
	    if (el.getElement('a.orderbutton')) {
	        el.getElement('a.orderbutton').addEvent('click', function(event) {
	            event.stop();
	            strQuantity = el.getElement('input[name="quantity"]').get('value');
	            addProductToOrder(strProductId, strQuantity, this);
	        });
	    }

	    if (el.getElement('a.altbutton')) {
	        el.getElement('a.altbutton').addEvent('click', function(event) {
	            event.stop();
	            strQuantity = el.getElement('input[name="quantity"]').get('value');
	            addProductToProposition(strProductId, strQuantity, this);
	        });
	    }
	});

	$$('table.order tr.order_product').each(function(el) {
	    if (el.getElement('td.options input[name="productId"]')) {
	        var strProductId = el.getElement('td.options input[name="productId"]').get('value');

	        if (el.getElement('a.delete')) {
	            el.getElement('a.delete').addEvent('click', function(event) {
	            event.stop();
                deleteProductInOrder(strProductId, this);
	            });
	        }
	    }
	});

	$$('table.proposition tr.order_product').each(function(el) {
	    if (el.getElement('td.options input[name="productId"]')) {
	        var strProductId = el.getElement('td.options input[name="productId"]').get('value');

	        if (el.getElement('a.delete')) {
	            el.getElement('a.delete').addEvent('click', function(event) {
                event.stop();
                deleteProductInProposition(strProductId, this);
	            });
	        }
	    }
	});

}

/**
* adds product(s) to order
*
* @param {string} id of product
* @param {string} quantity
* @param {object} DOM element which invoked this function
* 
* @author Klaas Dieleman <klaas{AT}efocus.nl>
* @since 1.0, 13 jan 2010
* @return void
*/
function addProductToOrder(strProductId, strQuantity, elButton) {
    new Request.JSON({
        url: '/layouts/webshop/Ajax.aspx/AddProductToOrder',
        data: "{'productId': '" + strProductId + "', 'quantity': '" + strQuantity + "'}",
        urlEncoded: false,
        headers: { 'Content-Type': 'application/json; charset=utf-8' },
        onSuccess: function() {
        showShopNotification(elButton, { 'text': sProductIsToegevoegdAanWinkelwagen });
            refreshUpdatePanel(sOrderPanelRefreshButtonClientId);
        },
        onFailure: function() {
        showShopNotification(elButton, { 'text': sErIsEenFoutOpgetreden })
        }
    }).post();
}

/**
* adds product(s) to proposition
*
* @param {string} id of product
* @param {string} quantity
* @param {object} DOM element which invoked this function
* 
* @author Klaas Dieleman <klaas{AT}efocus.nl>
* @since 1.0, 13 jan 2010
* @return void
*/
function addProductToProposition(strProductId, strQuantity, elButton) {

    new Request.JSON({
        url: '/layouts/webshop/Ajax.aspx/AddProductToProposition',
        data: "{'productId': '" + strProductId + "', 'quantity': '" + strQuantity + "'}",
        urlEncoded: false,
        headers: { 'Content-Type': 'application/json; charset=utf-8' },
        onSuccess: function() {
        showShopNotification(elButton, { 'text': sProductIsToegevoegdAanOfferte })
            refreshUpdatePanel(sPropositionPanelRefreshButtonClientId);
        },
        onFailure: function() {
        showShopNotification(elButton, { 'text': sErIsEenFoutOpgetreden })
        }
    }).post();
}

/**
* updates product in order
*
* @param {string} id of product
* @param {string} quantity (0 to remove)
* @param {object} DOM element which invoked this function
* 
* @author Dennis Velthuis <dennis.velthuis{AT}efocus.nl>
* @since 1.0, 14 jan 2010
* @return void
*/
function updateProductInOrder(strProductId, strQuantity, elButton) {
    new Request.JSON({
        url: '/layouts/webshop/Ajax.aspx/UpdateProductInOrder',
        data: "{'productId': '" + strProductId + "', 'quantity': '" + strQuantity + "'}",
        urlEncoded: false,
        headers: { 'Content-Type': 'application/json; charset=utf-8' },
        onSuccess: function() {
        showShopNotification(elButton, { 'text': sWinkelwagenIsBijgewerkt })
            if (strQuantity > 0) {
                refreshUpdatePanel(sBasketContentsPanelRefreshButtonClientId);
                refreshUpdatePanel(sOrderPanelRefreshButtonClientId);
            }
            else {
                refreshUpdatePanel(sBasketContentsPanelDeleteCommandClientId);
                refreshUpdatePanel(sOrderPanelRefreshButtonClientId);
            }
        },
        onFailure: function() {
        showShopNotification(elButton, { 'text': sErIsEenFoutOpgetreden })
        }
    }).post();
}

/**
* updates product in proposition
*
* @param {string} id of product
* @param {string} quantity (0 to remove)
* @param {object} DOM element which invoked this function
* 
* @author Dennis Velthuis <dennis.velthuis{AT}efocus.nl>
* @since 1.0, 14 jan 2010
* @return void
*/
function updateProductInProposition(strProductId, strQuantity, elButton) {

    new Request.JSON({
        url: '/layouts/webshop/Ajax.aspx/UpdateProductInProposition',
        data: "{'productId': '" + strProductId + "', 'quantity': '" + strQuantity + "'}",
        urlEncoded: false,
        headers: { 'Content-Type': 'application/json; charset=utf-8' },
        onSuccess: function() {
        showShopNotification(elButton, { 'text': sOfferteIsBijgewerkt })
            if (strQuantity > 0)
                refreshUpdatePanel(sBasketContentsPanelRefreshButtonClientId);
            else
                refreshUpdatePanel(sBasketContentsPanelDeleteCommandClientId);
        },
        onFailure: function() {
        showShopNotification(elButton, { 'text': sErIsEenFoutOpgetreden })
        }
    }).post();
}

/**
* deletes product in order
*
* @param {string} id of product
* @param {string} quantity (0 to remove)
* @param {object} DOM element which invoked this function
* 
* @author Dennis Velthuis <dennis.velthuis{AT}efocus.nl>
* @since 1.0, 14 jan 2010
* @return void
*/
function deleteProductInOrder(strProductId, elButton) {
    var result = confirm(sWiltUDitProductVerwijderen);

    if (result) {
        new Request.JSON({
            url: '/layouts/webshop/Ajax.aspx/RemoveProductInOrder',
            data: "{'productId': '" + strProductId + "', 'quantity': '0'}",
            urlEncoded: false,
            headers: { 'Content-Type': 'application/json; charset=utf-8' },
            onSuccess: function() {
                refreshUpdatePanel(sBasketContentsPanelDeleteCommandClientId);
            },
            onFailure: function() {
            showShopNotification(elButton, { 'text': sErIsEenFoutOpgetreden })
            }
        }).post();
    }
}

/**
* deletes product in proposition
*
* @param {string} id of product
* @param {string} quantity (0 to remove)
* @param {object} DOM element which invoked this function
* 
* @author Dennis Velthuis <dennis.velthuis{AT}efocus.nl>
* @since 1.0, 14 jan 2010
* @return void
*/
function deleteProductInProposition(strProductId, elButton) {
    var result = confirm('Wilt u dit product verwijderen?');

    if (result) {
        new Request.JSON({
            url: '/layouts/webshop/Ajax.aspx/RemoveProductInProp',
            data: "{'productId': '" + strProductId + "', 'quantity': '0'}",
            urlEncoded: false,
            headers: { 'Content-Type': 'application/json; charset=utf-8' },
            onSuccess: function() {
                refreshUpdatePanel(sBasketContentsPanelDeleteCommandClientId);
            },
            onFailure: function() {
            showShopNotification(elButton, { 'text': sErIsEenFoutOpgetreden })
            }
        }).post();
    }    
}

/**
* refreshes an update panel
*
* @param {string} id of button in panel responsible for refresh
*
* @author Dennis Velthuis <dennis.velthuis{AT}efocus.nl>
* @since 1.0, 15 jan 2010
* @return void
*/
function refreshUpdatePanel(strRefreshButtonClientId) {
    if (document.getElementById(strRefreshButtonClientId)) {
        document.getElementById(strRefreshButtonClientId).click();
    }
}

/**
* called after AJAX request has completed, required to re-initialize data picker and nubmer controllers
**
* @author Dennis Velthuis <dennis.velthuis{AT}efocus.nl>
* @since 1.0, 15 jan 2010
* @return void
*/
function endRequestHandler(sender, args) {
    if (args.get_error() == undefined) {
        var controlId = sender._postBackSettings.sourceElement.id;

        if (controlId.indexOf('BasketContents') > 0 || controlId.indexOf('DeleteItem') > 0) {
            initOrderButtons();
            initDatePicker();
            initNumberControllers();

            if (sOrderPanelRefreshButtonClientId) {
                //refreshUpdatePanel(sOrderPanelRefreshButtonClientId);
            }

            if (sPropositionPanelRefreshButtonClientId) {
               //refreshUpdatePanel(sPropositionPanelRefreshButtonClientId);
            }
        }

        if (controlId.indexOf('0_btnBasketSummary') > 0) {
            //refreshUpdatePanel(sPropositionPanelRefreshButtonClientId);
        }
    }
}

function ToggleAfleveradres(sender, spanClientId) {
    if (sender.checked) {
        document.getElementById(spanClientId).style.display = "none";

        var myVal = document.getElementById(rqAfleverStraatHuisnummer);
        myVal.enabled = false;

        var myVal = document.getElementById(rqAfleverPostcode);
        myVal.enabled = false;

        var myVal = document.getElementById(rqAfleverPlaats);
        myVal.enabled = false;
    }
    else {
        document.getElementById(spanClientId).style.display = "block";

        var myVal = document.getElementById(rqAfleverStraatHuisnummer);
        myVal.enabled = true;

        var myVal = document.getElementById(rqAfleverPostcode);
        myVal.enabled = true;

        var myVal = document.getElementById(rqAfleverPlaats);
        myVal.enabled = true;
    }
}

function ToggleNewCustomer(sender, spanClientId) {
    if (!sender.checked) {
        document.getElementById(spanClientId).style.display = "none";

        var myVal = document.getElementById(rqAfleverStraatHuisnummer);
        myVal.enabled = false;

        var myVal = document.getElementById(rqAfleverPostcode);
        myVal.enabled = false;
    }
    else {
        document.getElementById(spanClientId).style.display = "block";

        var myVal = document.getElementById(rqWachtwoord);
        myVal.enabled = true;

        var myVal = document.getElementById(rqWachtwoordControle);
        myVal.enabled = true;

        var myVal = document.getElementById(cmpWachtwoord);
        myVal.enabled = true;
    }
}

function RefreshBasket(strRefreshButtonClientId) {
    refreshUpdatePanel(strRefreshButtonClientId);
}

/**
* bugfix for conflict between mootools and Microsoft AJAX
**
* @author Dennis Velthuis <dennis.velthuis{AT}efocus.nl>
* @since 1.0, 14 jan 2010
* @return void
*/
Function.prototype.startsWith = function() { return false; };

/**
* equalizes height
*
* @param {array} array of elements
*
* @author Mirjam <mirjam{AT}efocus.nl>
* @since 1.0, 16 jun 2010
* @return void
*/

function equalizeHeight(arrElements) {
	
	if (arrElements.length == 0) return false;
	
	var intMaxHeight = 0;
	
	arrElements.each(function(el){
		var intHeight = el.getHeight() - (el.getStyle('padding-top').toInt() + el.getStyle('padding-bottom').toInt() + el.getStyle('border-top-width').toInt() + el.getStyle('border-top-width').toInt());
		if (intHeight > intMaxHeight) intMaxHeight = intHeight;
	});
	
	arrElements.each(function(el){
		el.setStyle('height', intMaxHeight);
	});	
}