Object.extend(document, {
    isDocReady: false,
    isDocLoaded: false,
    ready: function(fn) { Event.observe(document, "doc:ready", fn); },
    load: function(fn) { Event.observe(document, "doc:loaded", fn); }
});
Event.observe(document, "dom:loaded", function() {
    Event.fire(document, "doc:ready");
    document.isDocReady = true;
    if (document.isDocLoaded)
        Event.fire(document, "doc:loaded");
});
Event.observe(window, "load", function() {
    document.isDocLoaded = true;
    if (!document.isDocReady) return;
    Event.fire(document, "doc:loaded");
});
Event.observe(document, "click", function() {
    hideFilter.apply(this, arguments);
});


/* Use the two following functions */
document.ready(function(){
    //ok to run some code
});
document.load(function(){
    //ok for DOM manipulation
    Event.observe(document.body, 'mouseup', function(e) {
    	irwButtonPressed = false;
    });
    // Add mouseevts for IE for color filter header
    if (Prototype.Browser.IE){
        if($('filterByColor') != null){
            Event.observe($('filterByColor'), "mouseover", function() {
                toggleFilterColorBg();
            });
            Event.observe($('filterByColor'), "mouseout", function() {
                toggleFilterColorBg();
            });
        }
    }
	// Check if the base target should be set to _self since this is needed by IHP2 in the Kiosk
	if (window.dialogArguments) {
        var mArgs = window.dialogArguments;
        if (mArgs.kiosk) { 
            var vBase = document.createElement('base');
            vBase.setAttribute('target', '_self'); 
            document.getElementsByTagName('head')[0].appendChild(vBase);
        }
	}
    // Check for global slideshow array
    if(typeof(js_fn_SLIDE_SHOW_IDS) != 'undefined') {
        slideshow = new Slideshow();
	};
    
    $$('#main input').each(function(input) {    
        if (input.visible() && (input.id == 'partNumber' || input.id == 'txtQuantity' || input.id == 'quantity')) {   
            input.observe('keydown', function(event) { 
                if(event.keyCode == Event.KEY_RETURN) { 
                    if(input.up('#formShoppingListLeftNav')) {
                        // shopping list
                        onAddItemToShoppingList();
					} else if(input.up('#ArticleAddForm')) {
                        // shopping cart
                        respondToAddToCart();      
                    }
                }
			});
		}
	});
});

function irwInit() {
	if (navigator.platform.toLowerCase().indexOf('mac') != -1) {
		var css = new Element('link', {'href':'/ms/css/macos.css', 'type':'text/css', 'rel':'stylesheet'});
		$$('head')[0].insert(css);
	}
}

var irwButtonPressed = false;

/**
* This function is used by the createButton functions to prevent duplicate IDs on a page
*/
var buttons = new Hash();
function generateButtonID(_id) {
	var newid = _id;
	var counter = 0;
	if (buttons.get(newid) != null) {
		counter = parseInt(buttons.get(newid)) + 1;
		newid = _id + "_" + counter;
	}
	buttons.set(_id, counter);
	return newid;
}	

var buttonTemplate = new Template("<div class=\"buttonContainer\">" + 
    "<a id=\"#{buttonId}\" class=\"#{buttonClass}\" href=\"#\" onclick=\"return false;\">" +
        "<div class=\"buttonLeft#{buttonLeftClass}\">&nbsp;</div>" +
        "<div class=\"buttonCaption#{buttonCaptionClass}\">" + 
            "<input type=\"button\" value=\"#{buttonCaption}\" />" + 
        "</div>" + 
        "<div class=\"buttonRight#{buttonRightClass}\">&nbsp;</div>" + 
    "</a>" + 
"</div>");

var scriptTemplate = new Template("<script type=\"text/javascript\">\n" + 
    "Event.observe($('#{buttonId}'), 'click', function(e) { if (!this.hasClassName('disabledButton')) {#{buttonFunction};}});" + 
    "var input = $('#{buttonId}').down('input');" + 
    "Event.observe(input, 'mousedown' , function(e) { if (!this.hasClassName('pressed')) this.addClassName('pressed'); if (!this.hasClassName('down')) this.addClassName('down'); if (this.hasClassName('downNoMove')) this.removeClassName('downNoMove'); irwButtonPressed = true;	});" +
    "Event.observe(input, 'mouseup' , function(e) { if (this.hasClassName('down')) this.removeClassName('down'); if (this.hasClassName('pressed')) this.removeClassName('pressed'); if (this.hasClassName('downNoMove')) this.removeClassName('downNoMove'); });" +
    "Event.observe(input, 'mouseout' , function(e) {	if (this.hasClassName('down')) this.removeClassName('down'); if (this.hasClassName('downNoMove')) this.removeClassName('downNoMove'); var a = this.up('a'); if (a.hasClassName('hover')) a.removeClassName('hover'); });" +
    "Event.observe(input, 'mouseover' , function(e) { var a = this.up('a'); if (!a.hasClassName('hover')) a.addClassName('hover'); if (this.hasClassName('pressed')) { if (irwButtonPressed) {	this.addClassName('down'); this.addClassName('downNoMove');	} else { this.removeClassName('pressed');	}	}	});" +
"</script>");

/**
* Creates new button with caption, class and listener function
* The listener function only executes if the button is enabled,
* that is the button does not contains the class 'disabledButton' 
*
* Each button gets a unique id, like irw_button_1, irw_button_2, etc.
* The function returns the generated ID
*/
function createButton(_caption, _id, _class, _func) {
	//check if there is only three parameters
	if (typeof(_func) == "undefined") {
		//assume that no id is specified
		_func = _class;
		_class = _id;
		_id = "irw_button";
	}
	var newid = generateButtonID(_id);
	var obj = new Object();
	obj.buttonId = newid;
	obj.buttonClass = _class;
	obj.buttonCaption = _caption;
	obj.buttonSize = _caption.length;
	obj.buttonLeftClass = "";
	obj.buttonCaptionClass = "";
	obj.buttonRightClass = "";	
	var reg = new RegExp("([a-zA-Z]+)Button","g");
	var m = null;
	var c = "";
	while (m = reg.exec(_class)) {
		if (m[1] != "disabled") {
			c += " " + m[1];
		}
	}
	if (c.length > 0) {
		var tmp = c.substring(1).split(' ');
		for (var i=0;i<tmp.length;i++) {
			obj.buttonLeftClass += " " + "buttonLeft" + tmp[i].substring(0,1).toUpperCase() + tmp[i].substring(1);
			obj.buttonCaptionClass += " " + "buttonCaption" + tmp[i].substring(0,1).toUpperCase() + tmp[i].substring(1);
			obj.buttonRightClass += " " + "buttonRight" + tmp[i].substring(0,1).toUpperCase() + tmp[i].substring(1);
		}
	}
	document.write(buttonTemplate.evaluate(obj));
	Event.observe($(newid), 'click', function(e) {
		if (!this.hasClassName('disabledButton')) {
			_func(e); 
		}
	});
	var input = $(newid).down('input');
	Event.observe(input, 'mousedown' , function(e) {
		if (!this.hasClassName('pressed')) this.addClassName('pressed');	
		if (!this.hasClassName('down')) this.addClassName('down');
		if (this.hasClassName('downNoMove')) this.removeClassName('downNoMove');
		irwButtonPressed = true;
	});
	Event.observe(input, 'mouseup' , function(e) {
		if (this.hasClassName('down')) this.removeClassName('down');
		if (this.hasClassName('pressed')) this.removeClassName('pressed');			
		if (this.hasClassName('downNoMove')) this.removeClassName('downNoMove');
	});
	Event.observe(input, 'mouseout' , function(e) {
		if (this.hasClassName('down')) this.removeClassName('down');
		if (this.hasClassName('downNoMove')) this.removeClassName('downNoMove');
		var a = this.up('a');
		if (a.hasClassName('hover')) a.removeClassName('hover');
	});
	Event.observe(input, 'mouseover' , function(e) {
		var a = this.up('a');
		if (!a.hasClassName('hover')) a.addClassName('hover');
		if (this.hasClassName('pressed')) {
			if (irwButtonPressed) {
				this.addClassName('down');
				this.addClassName('downNoMove');				
			} else {
				this.removeClassName('pressed');
			}
		}
	});
}

/**
* This function creates a string with the button and a script tag,
* which creates the observer. It is used by commerce for creating content
* dynamically, for example in the "Add to shopping cart" popup window.
* 
* It works in the same way as the previous function, except that the _func
* parameter is a string representation of a existing javascript function
*/
function createButtonLayout(_caption, _id, _class, _func) {
	//check if there is only three parameters
	if (typeof(_func) == "undefined") {
		//assume that no id is specified
		_func = _class;
		_class = _id;
		_id = "irw_button";
	}
	var newid = generateButtonID(_id);
	var newfunc = _func + (_func.indexOf('(') == -1 ? '(e)' : '');
	var obj = new Object();
	obj.buttonId = newid;
	obj.buttonClass = _class;
	obj.buttonCaption = _caption;
	obj.buttonSize = _caption.length;
	obj.buttonLeftClass = "";
	obj.buttonCaptionClass = "";
	obj.buttonRightClass = "";
	obj.buttonFunction = newfunc;	
	var reg = new RegExp("([a-zA-Z]+)Button","g");
	var m = null;
	var c = "";
	while (m = reg.exec(_class)) {
		if (m[1] != "disabled") {
			c += " " + m[1];
		}
	}
	if (c.length > 0) {
		var tmp = c.substring(1).split(' ');
		for (var i=0;i<tmp.length;i++) {
			obj.buttonLeftClass += " " + "buttonLeft" + tmp[i].substring(0,1).toUpperCase() + tmp[i].substring(1);
			obj.buttonCaptionClass += " " + "buttonCaption" + tmp[i].substring(0,1).toUpperCase() + tmp[i].substring(1);
			obj.buttonRightClass += " " + "buttonRight" + tmp[i].substring(0,1).toUpperCase() + tmp[i].substring(1);
		}
	}
	
	return buttonTemplate.evaluate(obj) + scriptTemplate.evaluate(obj);
}

/**
* This function is used to hide all filter dropdowns (e.g. div layer)
*/
function hideFilter() {
	var iterations = 0;
	var isFilter = function(ele) {
		if (iterations++ >= 5) {
			return false;
		}
		
		if (ele.className) {
			if ((ele.className.indexOf("filterDropdowns") >= 0) || (ele.className.indexOf("filterDropdown") >= 0) || (ele.className.indexOf("filter") >= 0))  {
				return true;
			}
		}
		
		if (ele.tagName) {
			if (ele.tagName.toLowerCase() != "body") {
				return isFilter(ele.parentNode);
			}
		}
		
		return false;
	};
	if (isFilter(arguments[0].target)) return;

	$$('.filterDropdowns .filterDropdown').each(function(dd){
        dd.hide();
    });
    $$('#filterContainer .filter').each(function(btn){
        btn.removeClassName('filterActive');
    });
}

/**
* This function is used for show/hide of a filter dropdown (e.g. div layer)
* It is used on department/category pages to filter products in the product listing
* @param btn        The element clicked to show/hide dropdown
* @param filter		The dropdown layer to show/hide onclick
*/
function toggleFilter(btn,filter){
    var offL = -5;
    var offT = $('filterContainer').getHeight()-6;
    
    filter.clonePosition(btn,{setHeight:false, setWidth:false, offsetLeft:offL, offsetTop:offT});
    // Min width of dropdown should be same as button
    var btnW = btn.getWidth();
    var filterW = filter.getWidth();
    if(filterW < btnW){filter.setStyle({width:(btnW)+'px'})};
    
    // Hide all first (but myself)
    $$('.filterDropdowns .filterDropdown').each(function(dd){
        if(filter.id != dd.id){dd.hide();}
    });
    $$('#filterContainer .filter').each(function(dd){
        if(btn.id != dd.id){dd.removeClassName('filterActive');}
    });
    
    // Toggle the filter
    filter.toggle();
    btn.toggleClassName('filterActive');
}

/**
* Toggles background image (png) for color filter btn
*/
function toggleFilterColorBg(){
    var el = $$('.filter .color')[0];
    el.toggleClassName('colorHover');
}

/**
* Checks if the buyOnline container fits on the filter row. If not, displays it on the pagination row instead
* It is used on department/category pages 
*/
function printBuyOnline() {
    var fc = $('filterContainer').getWidth();
    var fbo = $('filterBuyableOnline') != null ? $('filterBuyableOnline').getWidth() : 0;
    var fbt = 0, fbc = 0, sb = 0;
    
    if($('filterByType') != null){ fbt = $('filterByType').getWidth() };
    if($('filterByColor') != null){ fbc = $('filterByColor').getWidth() };
    if($('sortBy') != null){ sb = $('sortBy').getWidth() };

    var btnW = fbt + fbc + sb;
    var contentW = fbo + btnW +5;
    
    if(contentW >= fc){
        $('paginationBuyableOnline').show();
        $('filterBuyableOnline').hide();                
    }
}

/**
* Shows all the compareRow rows in the product listing on page load. 
* This is because they should not be visible if user has no JS.
*/
function displayOfNoJsContent(){
    var prodContainer = $('productsContainer');
    if(prodContainer == null) return;
    var objects = prodContainer.select('.compareRow');
    objects.each(function(item) {
        item.show();
    });
}


/*  NLP Releated JS  */

function loadNlpProducts(placeHolder, marketCode, products) {
  //  alert(products.length);     
    var langs = marketCode.split("_");
    
    var params = "?type=xml&dataset=normal,prices,allimages,parentCategories";
    var prodTemplate = new Template("<div class=\"product\"><a class=\"image\" href=\"#{url}\"><img src=\"#{image}\" border=\"0\" /><img class=\"newLowerPriceImage\" src=\"/ms/flash/rooms_ideas/mpa2/images/logos/newlowerprice/#{market}/nlp_01.png\" border=\"0\" /></a><div class=\"name\">#{name}</div><div class=\"description\">#{description}</div><div class=\"link\"><a href=\"#{url}\">#{link}</a></div></div>");
    var btnTemplate = new Template("<a class=\"leftBtn\"   href=\"javascript:nlpMoveLeft('#{id}',#{count});\"></a><a href=\"javascript:nlpMoveRight('#{id}',#{count});\" class=\"rightBtn\"></a>");
    
    var addNlpProducts = function(xml) {

	     
        var p = xml.getElementsByTagName('product');
        var html = btnTemplate.evaluate({'id':placeHolder, 'count':products.length}); 
        html += "<div class=\"nlpClipArea\"><div class=\"products\" style=\"width:" + (142*products.length) + "px;\">";
        for (var i = 0; i < p.length; i++) {
            var obj = {};
            var item = p[i].getElementsByTagName('item')[0];
            obj.url = item.getElementsByTagName('URL')[0].childNodes[0].nodeValue;    
            obj.name = item.getElementsByTagName('name')[0].childNodes[0].nodeValue;
            obj.image = item.getElementsByTagName('images')[0].getElementsByTagName('thumb')[0].childNodes[0].childNodes[0].nodeValue;
            var price = item.getElementsByTagName('prices')[0].getElementsByTagName('normal')[0].getElementsByTagName('priceNormal')[0].childNodes[0].nodeValue;
            obj.description = products[i].description.replace('{0}',price);
            obj.link = products[i].link;
            obj.market = marketCode;
            html += prodTemplate.evaluate(obj);
        }
        html += "</div></div>";
            
        $(placeHolder).update(html);
                
    }    

    var requestUrl = "/" + langs[1].toLowerCase() + "/" + langs[0].toLowerCase() + "/catalog/products/";
    products.each(function(product) {
        requestUrl += product.id + ',';        
    });    
    requestUrl = requestUrl.substr(0,requestUrl.length-1) + params;
    
   // alert(requestUrl);
    
    new Ajax.Request(requestUrl, {
    	method: 'get',
    	contentType: 'application/xml',
    	onSuccess: function(response) {
    		addNlpProducts(response.responseXML);		
    	}
    });
            
}

function nlpMoveLeft(placeHolder, count) {
    var pDiv = $(placeHolder).select('.products')[0];
    var m = pDiv.style.width.match("([0-9]+)");
    var w = m != null && m.length > 0 ? m[0] : 0;
    var pw = w/count;
    m = pDiv.style.left.match("([0-9]+)");
    var cl = m != null && m.length > 0 ? m[0] : 0;
    var c = cl/pw;
    c = (c+count-1) % count;
    new Effect.Move(pDiv, { x: -c*pw, y: 0, mode: 'absolute', duration:0.0 });
}


function nlpMoveRight(placeHolder, count) {
    var pDiv = $(placeHolder).select('.products')[0];
    var m = pDiv.style.width.match("([0-9]+)");
    var w = m != null && m.length > 0 ? m[0] : 0;
    var pw = w/count;
    m = pDiv.style.left.match("([0-9]+)");
    var cl = m != null && m.length > 0 ? m[0] : 0;
    var c = cl/pw;
    c = (c+1) % count;
    new Effect.Move(pDiv, { x: -c*pw, y: 0, mode: 'absolute', duration:0.0 });    
}



/*  NLP Releated JS ENDS  */


/** 
    Global IOWS functions wrapped in the Iows namespace.
    Functions used to parse the IOWS xml returned and display it in HTML format.
*/

var Iows = {
    /** Base parameters for the call **/
    method: "get",
    type: "xml",
    contentType: 'application/xml',
    dataset: "normal,prices,allimages,parentCategories",

    /** Returns the value from a specific node
    * @param node       : The element representing the node
    * @param tagName    : The element representing the tagName
    * @return           : The node value if present, otherwise an empty string */
    getNodeVal: function(node,tagName){
        try{
            var val = node.getElementsByTagName(tagName)[0].firstChild.nodeValue;
        }catch(e){
            var val = "";
        }
        return val;
    },

    /** 
    * Extracts the measures from the measure node and uses a template to return the html snippet
    * @param node           : The element representing the measure node
    * @param dimTemplate    : The template to evaluate a dimension
    * @param template       : The template to evaluate and return the measures
    * @param moreText       : A string representing the "more" text
    * @param moreLink       : A string representing the link for the "more" text
    * @return               : The evaluated html snippet from the template */
    getMeasures: function(node,dimTemplate,template,moreText,moreLink){
        var measure = "";
        
        if(node != "null null" && node != "null"){
            var array = node.replace("</v></m></rm> <rm><m><d>", "</v></m><m><d>").replace("<rm><m><d>","").replace("</v></m></rm>","").split("</v></m><m><d>");
            var len = array.length;
            for (var i=0;i<len;i++){
                measure += dimTemplate.evaluate({dimension: array[i].replace("</d><v>",":&nbsp;")});
                if(i==2){break;}
            }
            measure = '<div class=\"dimensions\">' + measure + '</div>';
            
            if (len > 3) {
                measure = measure + template.evaluate({text: moreText, link: moreLink});
            }
        }
        return measure;
    },

    /** 
    * Checks if the product has any parent in series, systems or collections and returns the proper one
    * @param template   : The template to use to evaluate and return the html 
    * @param node       : The element representing the Item node
    * @return           : The evaluated html snippet from the template */
    getSSC: function(node,template){
        var categoryNames = new Array("collections","systems","series");
        var categories = node.getElementsByTagName("categories")[0];
        
        if(typeof(categories) != 'undefined' && categories != null){
            for(var i = 0; i < 3;i++){
                var tmp = categories.getElementsByTagName(categoryNames[i]);
                var category = tmp[0].getElementsByTagName("category");
                if(category != null && category.length > 0){
                    var ssc = {"name":this.getNodeVal(category[0],'name'),
                                "link":this.getNodeVal(category[0],'URL')};
                                
                    return template.evaluate(ssc);
                }
            }
        }else{
            return "";
        }
    },

    /**
    * Parses the price information an returns an object with the price information.
    * @param node   : The element representing the node
    * @return       : An object with the following properties set: price, pricePkg family, familyPkg */
    getPrices: function(node){
        var obj = new Object();
        var prices = node.getElementsByTagName("prices")[0];
        var normal = this.getPricePart(prices,"normal");
        obj.price = normal.price;
        obj.pricePkg = normal.pricePkg;
        var family = this.getPricePart(prices,"family-normal");
        obj.family = family.price;
        obj.familyPkg = family.pricePkg;
        var dual = this.getPricePart(prices,"second");
        obj.priceDual = dual.price;
        obj.priceDualPkg = dual.pricePkg;
        
        try{
            obj.prfCharge = prices.getElementsByTagName("normal")[0].getElementsByTagName("priceNormal")[0].getAttribute("prfChargeFormatted");
            obj.noPrfCharge = prices.getElementsByTagName("normal")[0].getElementsByTagName("priceNormal")[0].getAttribute("priceWithNoPrfChargeFormatted");
        }
        catch (err){}

        return obj;
    }, 

    /**
    * Retrieves the set price of a price node. 
    * The method returns "priceChanged" if set, otherwise "priceNormal" is returned.
    * @param node       : The element representing the "prices" node
    * @param tagName    : The name of the prices-node to retrieve the price from
    * @return           : An object with the following properties set: price, pricePkg */
    getPricePart: function(node,tagName){
        var obj = new Object();
        var normal = node.getElementsByTagName(tagName)[0];
        var unitPrice = node.getAttribute("unitPricePrimary");
        var suffix = "";
        var perUnit = "";
        
        // If unitprice attribute exists, add suffix to get price from PerUnit node
        if(unitPrice != null && unitPrice == "true"){
            suffix = "PerUnit";
            unitPrice = true;
        }
        
        // Test if price changed exists, else get normal price
        var price = this.getNodeVal(normal,"priceChanged"+suffix);
        if(price.blank()){
            obj.price = this.getNodeVal(normal,"priceNormal"+suffix);
            if(unitPrice){
                obj.pricePkg = this.getNodeVal(normal,"priceNormal");
                obj.price = obj.price + this.getUnitSuffix(normal,"priceNormal"+suffix);
            }
        }else{
            obj.price = price;
            if(unitPrice){
                obj.pricePkg = this.getNodeVal(normal,"priceChanged");
                obj.price = obj.price + this.getUnitSuffix(normal,"priceChanged"+suffix);
            }
        }
        
        return obj;
    },
    
    /**
    * The method returns a unit suffix from the <priceXxxxxPerUnit> node if it exists, otherwise an empty string.
    * @param node       : The element representing the price node
    * @param tagName    : The name of the price-node to retrieve the price from
    * @return           : The unit suffix  */
    getUnitSuffix: function(node,tagName){
        var suffix = "";
        try{
            var priceNode = node.getElementsByTagName(tagName)[0];
            unit = priceNode.getAttribute("unit");
            if(unit != null){
                suffix = " / " + unit;
            };
        }catch(err){};
        
        return suffix;
    }
}


