/*global $, $$, defaultSearchText*/
var defaultSearchText = 'Enter product code or keywords';
window.onload = function ()
{		
	var searchTextInput = $('searchTextInput');
	if (searchTextInput) {	
		searchTextInput.value = defaultSearchText;
		searchTextInput.observe('blur', function () {
			if (searchTextInput.value == '') {
				searchTextInput.value = defaultSearchText;
			}
		});
		searchTextInput.observe('click', function () {		
			if (searchTextInput.value == defaultSearchText) {
				searchTextInput.value = '';
			}	
		});
		searchTextInput.up('form').observe('submit', function(event) {
			if (searchTextInput.value == defaultSearchText) {
				event.stop();
			}
		});
	}	
	$$('table#filters tbody td span').invoke('observe', 'click', function() {
		$$('table#filters tbody td a.hidden').each(function(item) {
		    
			//item.removeAttribute('class');
			item.removeClassName('hidden');
		});
		$$('table#filters tbody td span').each(function(item){
		    item.remove();
		});
		//this.remove();
	});
	var zlimit = $('zlimit');
    if (zlimit) {
        zlimit.observe('change', function() {
            zlimit.up('form').submit();
        });
    }	
	var zsortby = $('zsortby');
    if (zsortby) {
        zsortby.observe('change', function() {
            zsortby.up('form').submit();
        });
    }
    if (document.getElementById('secureCodeRedirect')) {
		document.getElementById('secureCodeRedirect').submit();
	}
	var myHelp = $('cvvhelp');
	if (myHelp) {	
		constructMyHelp();
		var myHelpPopup = $('my-help-popup');
		if (myHelpPopup) {
			myHelp.observe('click', function() {
				myHelpPopup.show();
			});
			myHelp.show();
		}
	}
	var postCodeSubmit = $('post-code-submit');
	if (postCodeSubmit) {
		postCodeSubmit.observe('click', function (event) {
			Event.stop(event);
			var postcode_suite;
			var postcode_prodcat;
			var postcode_subcat;
			var postcode_matnr;
			var postcode;
			if ($('zdeldate_suite')) {
				postcode_suite = $('zdeldate_suite').value;
			}
			if ($('zdeldate_prodcat')) {
				postcode_prodcat = $('zdeldate_prodcat').value;
			}
			if ($('zdeldate_subcat')) {
				postcode_subcat = $('zdeldate_subcat').value;
			}
			if ($('zdeldate_matnr')) {
				postcode_matnr = $('zdeldate_matnr').value;
			}
			if ($('zpostcode')) {
				postcode = $('zpostcode').value;
			}
			getDelDates(postcode, '28', postcode_suite, postcode_prodcat, postcode_subcat, postcode_matnr, '1', '4');		
		})
	}
	$$('input.configurator-action').invoke('observe', 'click', function() {
		var action = this.next("input[type='hidden']");
		if (action) {
			if (action.value != '') {			
				document.location = action.value;
			}
		}		
	});	
	new BuyPopUp();
	correctPNG();
}
function constructMyHelp()
{
	var paymentFields = $('paymentFields');
	if (paymentFields) {
		paymentFields.appendChild(Builder.node('div', {id:'my-help-popup'}, [
			Builder.node('span', {id:'my-help-popup-close'}, 'Close'),
			Builder.node('img', {src:'/ui/img-cvv-help.jpg', title:'Last 3 Numbers on back of card', alt:'Last 3 Numbers on back of card'}),
			Builder.node('strong', 'Electron Visa, Maestro, MasterCard, Visa'),
			Builder.node('p', 'Last 3 Numbers on back of card')
		]));	
		$('my-help-popup').hide();
		$('my-help-popup-close').observe('click', function() {
			$('my-help-popup').hide();
		});
		
	}
}
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
  var arVersion = navigator.appVersion.split("MSIE");
  var version = parseFloat(arVersion[1]);
  if ((version >= 5.5) && (document.body.filters)) 
  {
    for(var i=0; i<document.images.length; i++)
    {
      var img = document.images[i];
      var imgName = img.src.toUpperCase();
	  var paramLoc = imgName.indexOf("?");
	  
	  if (paramLoc != -1)
	  {
		  if (imgName.substring(paramLoc-3, paramLoc) == "PNG"  && img.src.indexOf('google') == -1 && img.className == 'overlay')
	      {
	        var imgID = (img.id) ? "id='" + img.id + "' " : "";
	        var imgClass = (img.className) ? "class='" + img.className + "' " : "";
	        var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
	        var imgStyle = "display:inline-block;" + img.style.cssText ;
	        var cssClass = img.className;
	        if (img.align == "left") imgStyle = "float:left;" + imgStyle;
	        if (img.align == "right") imgStyle = "float:right;" + imgStyle;
	        if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
	        var strNewHTML = "<span " + imgID + imgClass + imgTitle
	        + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	        + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	        + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
	        img.outerHTML = strNewHTML;
	        i = i-1;
	      }
	  }
	  else
	  {
		  if (imgName.substring(imgName.length-3, imgName.length) == "PNG"  && img.src.indexOf('google') == -1 || img.className == 'overlay')
	      {
	        var imgID = (img.id) ? "id='" + img.id + "' " : "";
	        var imgClass = (img.className) ? "class='" + img.className + "' " : "";
	        var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
	        var imgStyle = "display:inline-block;" + img.style.cssText ;
	        var cssClass = img.className;
	        if (img.align == "left") imgStyle = "float:left;" + imgStyle;
	        if (img.align == "right") imgStyle = "float:right;" + imgStyle;
	        if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
	        var strNewHTML = "<span " + imgID + imgClass + imgTitle
	        + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	        + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	        + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
	        img.outerHTML = strNewHTML;
	        i = i-1;
	      }
	  }
    }
  }
}
function getDelDates(postcode, siteKey, suiteKey, prodcatKey, subcatKey, matnr, qty, noOfDates)
{
	var loader = document.createElement('div');
	loader.id = 'deliveryDatesLoad';
	loader.style.display = '';
	
	var myAJAXUrl = "/delivery_dates.xml?zpstlz=" + postcode +  
                    "&zsuite=" + suiteKey + 
                    "&zprodcat=" + prodcatKey + 
			        "&zsubcat=" + subcatKey +
			        "&zmatnr=" + matnr + 
			        "&zquantity=" + qty + 
			        "&zdates_count=" + noOfDates;

    new Ajax.Updater('matDatesAJAXContainer', myAJAXUrl, {
		method: 'post',
		onSuccess: function(transport) {
			$('matDatesAJAXContainer').show();
		},
		onComplete: function(transport) {
			$('deliveryDatesLoad').hide();
		}	
	});
}
function clearDates()
{
	removeChildren($('matDatesAJAX'));
}
/* Calendar Stuff */
function selectDate(itemRef, newDate)
{
	var selectedDate = $('selectedDate');
	if (itemRef){
		var flag = false;
		var myCounter = 0;
		var x = 0;
		var myDate;
		selectedDate.value = newDate;
		var myDate = $('delDateInfo');
		var myError = $('calError');
		if (myDate){
			myText = document.createTextNode('Your chosen delivery date is ' + newDate.substring(6,8) + '.' + newDate.substring(4,6) + '.' + newDate.substring(0,4));
			while(myDate.lastChild){
				myDate.removeChild(myDate.lastChild);
			}
			myDate.appendChild(myText);
			if (myError){
				myError.hide();
			}
		}
		var eltArray = document.getElementsByTagName('td');
		if (eltArray){
			for (x = 0; x < eltArray.length; x++){
				if (eltArray[x].className == 'calCellSelected'){
					myCounter++;
				}
			}
		}
		if (myCounter > 0){
			for (x = 0; x < eltArray.length; x++){
				if (eltArray[x].className == 'calCellSelected'){
					eltArray[x].className = 'calCellLink';
				}
			}
		}
		itemRef.className = 'calCellSelected';
		myCounter = 0;
	}
}
function calNextMonth(hx,sx){var h=$(hx);var s=$(sx);if(h){if(s){h.style.display='none';s.style.display='block';}}}
function changeDateText(d){var a =$('calendarInstruction');if(a){n=a.childNodes;for(var i=n.length-1;i>=0;i--){a.removeChild(n[i]);}var t=document.createTextNode('You have selected '+d.substring(6,8)+'/'+ d.substring(4,6)+'/'+d.substring(0,4)+' as your delivery date.');a.appendChild(t);}}
function checkLength(element, length){if (element){if (length > 0){myValue = getValue(element);if (myValue.length > length){myNewValue = myValue.substring(0, length);setValue(element, myNewValue);}}}}
function getValue(element){if (element){if (element.value || element.value == ''){return element.value;}else if (element.lastChild){return element.lastChild.nodeValue;}else{return element.nodeValue;}}}
function setValue(element, value){if (element){if (element.value || element.value == ''){element.value = value;}else if (element.lastChild){element.lastChild.nodeValue = value;}else{element.nodeValue = value;}}}
/* Buy popup */
var BuyPopUp = Class.create({
	
	initialize: function() {		
		this.updateBuyPopUpList();
		this.insertHTML();		
	},

	insertHTML: function() {
		var objBody = $$('body')[0];
		if(objBody){
	    objBody.appendChild(Builder.node('div', {id:'buyPopUpOverlay'}));
	    objBody.appendChild(Builder.node('div', {id:'buyPopUp'}, [
		    Builder.node('div', {id:'buyPopUpInner'}, [
			    Builder.node('div', {id:'buyPopUpTop'}),
			    Builder.node('div', {id:'buyPopUpBottom'}, [
				    Builder.node('div', {id:'buyPopUpBottomLeft'}, [
					    Builder.node('span', {id:'buyPopUpBottomLeftSpan'}, 'Continue Shopping')
				    ]),
				    Builder.node('div', {id:'buyPopUpBottomRight'}, [
				      Builder.node('a', {href:'/order/basket'}, 'Checkout')
				    ])			
			    ])
	      ])
	    ]));
		
		var th = this;
    (function(){
      var ids = 'buyPopUpOverlay buyPopUp buyPopUpTop buyPopUpBottomLeft buyPopUpBottomRight buyPopUpBottomLeftSpan buyPopUpBottomRightSpan';   
      $w(ids).each(function(id){ th[id] = $(id); });
    }).defer();
    
    //this.buyPopUpOverlay = $('buyPopUpOverlay');
  
    $('buyPopUpOverlay').hide();
		$('buyPopUp').hide()
    $('buyPopUpBottomLeftSpan').observe('click', (function() { this.close(); }).bind(this));
	}  },
	
	updateBuyPopUpList: function() {
		document.observe('click', (function(event){
			var target = event.findElement('input[id^=addToBagItem]');
			if (target) {
				event.stop();
				this.buy('item');	
			}
		}).bind(this));
		document.observe('click', (function(event){
			var target = event.findElement('input[id^=addToBagSuite]');
			if (target) {
				event.stop();
				this.buy('suite');	
			}
		}).bind(this));
	},
	
	buy: function(type) {
		var quantity = '1';
		var url = '/add_to_basket.xml';	
		new Ajax.Request(url, {
			method: 'post',
			parameters: {zaction:type, zquantity:quantity},
			onSuccess: function(transport) {
				var response = $(transport.responseXML);
				if (response) {
					var root = response.getElementsByTagName('addtobasket')[0];
					var itemString = 'items';
					if (root.getElementsByTagName('items')[0].lastChild.nodeValue == 1) {
						itemString = 'item';
					}
					$('buyPopUpTop').update('<p>You have added this item.</p><p>You have ' + root.getElementsByTagName('items')[0].lastChild.nodeValue + ' ' + itemString + ' in your basket.</p>');
					$('basket-items').innerHTML  = root.getElementsByTagName('items')[0].lastChild.nodeValue + " items";
					$('basket-total').innerHTML  = "Total: " + root.getElementsByTagName('total')[0].lastChild.nodeValue;
					
					//$('headerBagItems').innerHTML  = root.getElementsByTagName('items')[0].lastChild.nodeValue + " ITEMS - " + root.getElementsByTagName('total')[0].lastChild.nodeValue;
					new Effect.Appear($('buyPopUpOverlay'), { duration: 0, from: 0.0, to: 0.7 });
         	        $('buyPopUp').show();
        }					
			}	
		});
		this.start();
	},
		
	start: function() {
		var arrayPageSize   = this.getPageSize();
		var arrayPageScroll = document.viewport.getScrollOffsets();
		var buyPopUpTop     = arrayPageScroll[1] + (document.viewport.getHeight() / 5);
		var buyPopUpLeft    = arrayPageScroll[0];
		
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
		
		this.buyPopUpOverlay.setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });		
		this.buyPopUp.setStyle({ top: buyPopUpTop + 'px', left: buyPopUpLeft + 'px' });
	},
	
	close: function() {
		this.buyPopUpOverlay.hide();
		this.buyPopUp.hide();
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
	},
	
	getPageSize: function () {
		var xScroll, yScroll, windowWidth, windowHeight;		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else {
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}			
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		return [pageWidth,pageHeight];
	}	
});