﻿document.observe("dom:loaded", function() {
	// highlight left nav
	var eanCode = jQuery("#eanCode").text();
	var eanOptionCode = 'ean' + eanCode;
	if (eanCode) {
		jQuery('#' + eanOptionCode).addClass("strong");
	}
	

	var menuItems = $("normalMenuList").select('li');
	menuItems.each(function(item) {
		var anchor = item.select('a')[0];
		anchor.observe('click', getNormalDealers);
	});

	menuItems = $("alphabeticMenuList").select('li');
	menuItems.each(function(item) {
		var anchor = item.select('a')[0];
		anchor.observe('click', getDealersByAlpha);
	});

	menuItems = $("postalCodeMenuList").select('li');
	menuItems.each(function(item) {
		var anchor = item.select('a')[0];
		anchor.observe('click', getDealersByPostal);
	});

	menuItems = $("leftNavDealers").select('li');
	menuItems.each(function(item) {
		var anchor = item.select('a')[0];
		anchor.observe('click', getDealersForEANcode);

		var anchor = item.select('a')[1];
		anchor.observe('click', getDealersForEANcode);
	});

	// add click events to top level filter options
	$("allPartnerShop").select("a")[0].observe('click', getDefaultNormalDealers);
	$("allShopAlphabetic").select("a")[0].observe('click', getDefaultDealersByAlpha);
	$("allShopPostalCode").select("a")[0].observe('click', getDefaultDealersByPostal);

	// set up the filter options
	$("allPartnerShop").select("a")[0].addClassName("strong");
	$("normalMenuList").select("li")[0].addClassName("strong");
	$("alphabeticMenuList").hide();
	$("postalCodeMenuList").hide();

	// create the paging
	createPaging('desato.paging', 'dealers', 'paging', 12, 'pagingItem', 'page');
	$('feedbackPanel').hide();

	setProdVariationData(eanCode);
}); 

function getDefaultNormalDealers(event) {

    var eanCode = $('eanCode').innerHTML;
    getCommerceConnectShops(eanCode, 'normal', "all");

    activateMainFilter(event.element().ancestors()[0]);

    return false;
}

function getNormalDealers(event) {

    var id = event.element().getAttribute('id');
    var eanCode = $('eanCode').innerHTML;
    getCommerceConnectShops(eanCode, 'normal', id);

    activateSubFilter(event.element().ancestors()[0]);

    return false;
}

function getDefaultDealersByAlpha(event) {

    var eanCode = $('eanCode').innerHTML;
    getCommerceConnectShops(eanCode, 'alphabetic', "af");

    activateMainFilter(event.element().ancestors()[0]);

    return false;
}

function getDealersByAlpha(event) {

    var id = event.element().getAttribute('id');
    var eanCode = $('eanCode').innerHTML;
    getCommerceConnectShops(eanCode, 'alphabetic', id);

    activateSubFilter(event.element().ancestors()[0]);

    return false;
}

function getDefaultDealersByPostal(event) {

    var eanCode = $('eanCode').innerHTML;
    getCommerceConnectShops(eanCode, 'postalCode', "0");

    activateMainFilter(event.element().ancestors()[0]);

    return false;
}

function getDealersByPostal(event) {

    var eanCode = $('eanCode').innerHTML;
    
    var id = event.element().getAttribute('id');
    var re = new RegExp('n', "g");
    id = id.replace(re,'');

    getCommerceConnectShops(eanCode, 'postalCode', id);
    
    activateSubFilter(event.element().ancestors()[0]);
    
    return false;
}

function getDealersForEANcode(event) {

    var eanCode = (event.element().ancestors()[0]).getAttribute('id');
    var re = new RegExp('ean_|ean', "g");
            
    getCommerceConnectShops(eanCode.replace(re,''), $('filterType').innerHTML, $('filterValue').innerHTML);

    var menuItems = $("leftNavDealers").select('li');    
    menuItems.each(function(item) 
    {
        var itemEan = item.getAttribute('id');
        if (itemEan == eanCode) {
            item.addClassName("strong");
        } else {
            item.removeClassName("strong");
        }
    });

    return false;
}

function activateMainFilter(mainFilterOption) {
    
    mainFilterOption.siblings().each(function(item) 
    {
        item.select("a")[0].removeClassName("strong");
        item.select("ul")[0].hide();
    });
    
    mainFilterOption.select("a")[0].addClassName("strong");
    activateSubFilter(mainFilterOption.select("li")[0]);
    mainFilterOption.select("ul")[0].show();
}

function activateSubFilter(subFilterOption) {

    subFilterOption.siblings().each(function(item) 
    {
        item.removeClassName("strong");
    });
    subFilterOption.addClassName("strong");
}

function getCommerceConnectShops(eanCode, filterType, filterValue) 
{
    $('feedbackPanel').hide();

    var params = Object.toJSON({
        "eanCode":eanCode, 
        "filterType":filterType, 
        "filterValue":filterValue
    });
    
    document.body.style.cursor= 'wait';
    new Ajax.Request('/' + locale + '/GetCommerceConnectorShops.json',
    {
    	method: 'get',
    	parameters: { useResponseBody: 'true', jsonString: params },
    	onSuccess: function(transport) {
    		var json = transport.responseText.evalJSON();
    		switch (json.type) {
    			case "JsonMethodMessage":
    				if (json.userMessage == null) {
    					DisplayShopList(json.result.shops);
    					$('eanCode').update(eanCode);
    					$('filterType').update(filterType);
    					$('filterValue').update(filterValue);
    					updateVariationData(eanCode);
    				} else {
    					$('dealers').update();
    					$('paging').hide();
    					$('feedbackPanel').addClassName("information");
    					$('feedbackPanel').update($('noDelersFoundLabel').innerHTML);
    					$('feedbackPanel').show();
    				}
    				break;

    			case "JsonValidationMessage":
    				handleValidationError('feedbackPanel', json.messages);
    				break;

    			case "JsonSystemExceptionMessage":
    				handleSystemExceptionError('feedbackPanel', json.message);
    				break;
    		}
    	},
    	onFailure: function() {
    		handleSystemExceptionError('feedbackPanel', json.message);
    	},
    	onComplete: function() {
    		document.body.style.cursor = 'default';
    	}
    })
}

function DisplayShopList(shopList)
{
   var i = 1;
   var innerHtml = "";
   
   $('feedbackPanel').hide();
   $('paging').show();
   $('dealers').update();

   shopList.each(function(item) 
   {
        innerHtml += "<div id=page"+i+" class=\"pagingItem\">";
        innerHtml += "<img src="+ item.logo+" alt="+ item.logo +"/> ";
        innerHtml += "<div class=\"commerceConnectorDiv\"><a class=\"button commerceConnectorBtn\" target=\"_blank\" href="+item.deepLink+"><span>"+ $('goToStoresLabel').innerHTML +"</span></a></div></div>";
        innerHtml += "</div>";
        i++;
   });

  $('dealers').update(innerHtml);
  createPaging('desato.paging', 'dealers', 'paging', 12, 'pagingItem', 'page'); 
}

function updateVariationData(eanCode) {
	var variationData = variationDataArray[eanCode];

	$("productSku").select('span')[0].update(variationData.sku);
	$("midFindStores").select('img')[0].setAttribute("src", variationData.prodImage);
}

function setProdVariationData(eanCode) {

	var variationData = variationDataArray[eanCode];
	
	$("productSku").select('span')[0].update(variationData.sku);
	
	prodImage = document.createElement("img");
	prodImage.setAttribute("width", "95");
	prodImage.setAttribute("height", "95");
	prodImage.setAttribute("border", "0");
	prodImage.setAttribute("src", variationData.prodImage);

	$('midFindStores').insertBefore(prodImage, $('midFindStores').firstChild);
}
