/**
 * 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 () {
        initMainNav();
        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'));
    }
});

/**
* initialises main menu functionality
* @author Rocco Janse, <rocco@efocus.nl>
* @return void
*/
function initMainNav() {

    if (document.id(document.body).getElement('ul.mainnav')) {
        var navcontainer = document.id(document.body).getElement('ul.mainnav');
        var nav = navcontainer.getChildren('li');

        nav.each(function (item) {
            if (item.hasClass('logo') == false) {
                var timer;
                item.addEvents({
                    'mouseenter': function () {
                        clearTimeout(timer);
                        activateNav(item);
                    },
                    'mouseleave': function () {
                        if (item.getElement('ul')) {
                            //timer = (function () {
                                item.removeClass('hover');
                                item.getElement('ul').style.display = 'none';
                                //item.getElement('ul').setStyle('display', 'none');
                           //}).delay(4000);
                        }
                    }
                });
            }
        } .bind(this));
        activateNav();
    }
}

/**
* activates nav items of main navigation
* @author Rocco Janse, <rocco@efocus.nl>
* @param {object} selected object
* @return void
*/
function activateNav(sel) {
    var navcontainer = document.id(document.body).getElement('ul.mainnav');
    var nav = navcontainer.getChildren('li');
    nav.each(function (item) {
        item.removeClass('hover');
        if (item.getElement('ul')) {
            item.getElement('ul').style.display = 'none';
            //item.getElement('ul').setStyle('display', 'none');
        }
        if (sel == item) {
            item.addClass('hover');
            if (item.getElement('ul')) {
                item.getElement('ul').style.display = 'block';
                //item.getElement('ul').setStyle('display', 'block');
            }
        }
    });
}

/**
* 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() {
    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.id(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 = document.id(document.body).getElements('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() {
    if (document.getElements('input.numbercontrol')) {
        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});

}

/**
* creates and shows shop notification
* @author Rocco Janse, <rocco@efocus.nl>
* @return void(0)
*/
function showShopNotification() {

    window.scrollTo(0, 0);

    /**
      EDIT Robert Jongkind, <robert.jongkind@efocus.nl>
      Gebruikt argument 0 (de knop die de ajax request initialiseert
      en checkt de classname om zo te bepalen wat voor type order het betreft
      **/
    var isOrder = arguments[0].className.contains('order');
    var isProposition = arguments[0].className.contains('altbutton');
    var orderType = '';
    isOrder ? orderType = 'order' : orderType = 'proposition';
    //Einde edit

    var boxWidth = 500;
    var boxHeight = 465;
    var viewportHeight = document.id(document.body).getHeight();
    var wrapperHeight = document.id(document.body).getElement('div.pagewrapper').getHeight();
    var viewportWidth = document.id(document.body).getWidth();
    var scollHeight = document.id(document.body).getScroll().y;

    var overlay = new Element('div', {
        'class': 'overlay',
        'id': 'overlay',
        'styles': {
            'position': 'absolute',
            'top': 0,
            'left': 0,
            'width': viewportWidth,
            'height': wrapperHeight,
            'background-color': '#000',
            'z-index': 998
        },
        'events': {
            'click': function () {
                hideShopNotification();
            }
        }
    });

    var box = new Element('iframe', {
        'frameborder': 'none',
        'class': 'msgbox',
        'id': 'msgbox',
        'src': 'http://' + document.location.hostname + '/shop/popup.aspx?orderType='+orderType,
        'styles': {
            'position': 'absolute',
            'top': scollHeight + Math.floor((viewportHeight - boxHeight) / 2),
            'left': Math.floor((viewportWidth - boxWidth) / 2),
            'width': boxWidth,
            'height': boxHeight,
            'z-index': 999
        }
    });

    overlay.fade('hide');
    overlay.inject(document.body);
    overlay.fade(0.4).get('tween').chain(function () {
        box.inject(document.body);
    });
}

/**
 * hides (destroys) shop notification
 * @author: Rocco Janse, <rocco@efocus.nl>
 * @param {object} parent element [optional]
 * @return void(0)
 */
function hideShopNotification(el) {

    if (el) {
        var overlay = document.id(el.document.body).getElement('#overlay');
        var box = document.id(el.document.body).getElement('#msgbox');
    } else {
        var overlay = document.id(document.body).getElement('#overlay');
        var box = document.id(document.body).getElement('#msgbox');
    }

    if (overlay) { overlay.dispose() }
    if (box) { box.dispose() }
}

/**
* 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() {

    document.id(document.body).getElements('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);
	        });
	    }
	});

	document.id(document.body).getElements('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);
	            });
	        }
	    }
	});

	document.id(document.body).getElements('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);
	});
}

/**
* Sorts productoverview and maintains querystring
*
*
* @author Robert J. <robert{AT}efocus.nl>
* @since SEO update, 25 may 2011
* @return void
*/

function sortProductOverview(dropDownList) {
  var q = window.location.search.substring(1);
  var data = parseQueryString(q);
  var sortValue = dropDownList.options[dropDownList.selectedIndex].value;
  data[sSorteerParameter] = sortValue;
  var newQueryString = getQueryString(data);

  window.location = getDocumentBasePath() + '?' + newQueryString;
}


/**
* Parses querystring to object
* 
*
* @author Robert J. <robert{AT}efocus.nl>
* @since SEO update, 25 may 2011
* @param string "var=val&var2=val2"
* @return object {var:'val',var2:'val2'}
*/
function parseQueryString(query) {
  var vars = query.split("&");
  var obj = {};

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    obj[pair[0]] = pair[1];
  }

  return obj;
}

/**
* Parses object to querystring
* 
*
* @author Robert J. <robert{AT}efocus.nl>
* @since SEO update, 25 may 2011
* @param object {var:'val',var2:'val2'}
* @return string "var=val&var2=val2"
*/
function getQueryString(values) {
  var str = '';
  var c = 0;

  for (var key in values) {
    if (!key) continue;
    if (c > 0) str += "&";
    str += key + "=" + values[key];
    c++;
  }

  return str;
}

/**
* Returns base path
* 
*
* @author Robert J. <robert{AT}efocus.nl>
* @since SEO update, 25 may 2011
* @return string
*/
function getDocumentBasePath() {
  var url = location.href;
  var url_parts = url.split("?");
  var main_url = url_parts[0]; 
  return main_url;
}
