clicked = false;
Ext.BLANK_IMAGE_URL='/gfx/blank.gif';

var searchBoxStatus = true;
var searchUserBoxStatus = true;

function errorHandler(message)
{
	$('disabledZone').style.visibility = 'hidden';
    if (typeof message == "object" && message.name == "Error" && message.description)
    {
        alert("Error: " + message.description);
    }
    else
    {
        alert(message);
    }
};

function sort(u)
{
	document.location = u;
}

Ext.override(Ext.form.ComboBox, {
	initEvents : function(){
		Ext.form.ComboBox.superclass.initEvents.call(this);
		this.keyNav = new Ext.KeyNav(this.el, {
			"up" : function(e){
				this.inKeyMode = true;
				this.selectPrev();
			},
			"down" : function(e){
				if(!this.isExpanded()){
					this.onTriggerClick();
				}else{
					this.inKeyMode = true;
					this.selectNext();
				}
			},
			"enter" : function(e){
				this.onViewClick();
				this.delayedCheck = true;
				this.unsetDelayCheck.defer(10, this);
			},
			"esc" : function(e){
				this.collapse();
			},
			"tab" : function(e){
				if(this.forceSelection) {
					this.onViewClick(false);
				} else {
					this.collapse();
				}
				return true;
			},
			scope : this,
			doRelay : function(foo, bar, hname){
				if(hname == 'down' || this.scope.isExpanded()){
				   return Ext.KeyNav.prototype.doRelay.apply(this, arguments);
				}
				return true;
			},
			forceKeyDown : true
		});
		this.queryDelay = Math.max(this.queryDelay || 10,
				this.mode == 'local' ? 10 : 4000);
		this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
		if(this.typeAhead){
			this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
		}
		if(this.editable !== false){
			this.el.on("keyup", this.onKeyUp, this);
		}
		if(this.forceSelection){
			this.on('blur', this.doForce, this);
		}
	},
	onLoad : function(){
		if(!this.hasFocus){
			return;
		}
		if(this.store.getCount() > 0){
			this.expand();
			this.restrictHeight();
			if(this.lastQuery == this.allQuery){
				if(this.editable){
					this.el.dom.select();
				}
				if(this.forceSelection && !this.selectByValue(this.value, true)){
					this.select(0, true);
				}
			}else{
				if(this.forceSelection){
					this.selectNext();
				}
				if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
					this.taTask.delay(this.typeAheadDelay);
				}
			}
		}else{
			this.onEmptyResults();
		}
	},
	onViewClick : function(doFocus){
		var index = this.view.getSelectedIndexes()[0];
		var r = this.store.getAt(index);
		if(r){
			this.onSelect(r, index);
		} else {
			this.collapse();
		}
		if(doFocus !== false){
			this.el.focus();
		}
	}
});

Ext.onReady(function() 
{

	// get the widget
	var e = Ext.get("fldProduct");
	e.focus();
	
	// Custom rendering Template
	var resultTpl = new Ext.XTemplate(
	    '<tpl for="."><div class="search-item"><div class="label"><h3>{name}</h3><div class="subinfo">Bijvoorbeeld: {extra}</div></div>',
	    '</span><div class="clr"></div></div></tpl>'
	);

	var ds = new Ext.data.Store({
	    proxy: new Ext.data.ScriptTagProxy({
	        url: 'data.cfm'
	    }),
	    reader: new Ext.data.JsonReader({
	        root: 'results'
	    }, [
	        {name: 'id', mapping: 'id'},
	        {name: 'name', mapping: 'name'},
	        {name: 'resultcount', mapping: 'resultcount'},
	        {name: 'extra', mapping: 'extra'}
	    ]),
		baseParams: {
	        r: 'producttitles'
	    }
	});
	
	
	var cbSearch = new Ext.form.ComboBox({
	    store: ds,
	    displayField: 'displayProducts',
	    typeAhead: false,
	    minChars: 3,
	    forceSelection: false,
	    loadingText: 'Bezig met zoeken...',
	    allowBlank: false,
	    selectOnFocus: true,
	    width: 300,
		listWidth : 400,
		enableKeyEvents:  true,
	    tpl: resultTpl,
	    applyTo: 'fldProduct',
	    itemSelector: 'div.search-item',
	    onSelect: function(record)
	    { 
			document.getElementById('fldProduct').value = record.data.name;
			document.getElementById('frmProductSearch').submit();
	    }
	});
	
	cbSearch.on('keypress', function(f, e) {
		if (e.getCharCode() == e.ENTER)
		{
			document.getElementById('frmProductSearch').submit();
		}	
	});


	cbSearch.on('collapse', function(f, e) 
	{
			document.getElementById('frmProductSearch').submit();
	});

	
	
		
	
	if (getCookie('searchUserBoxStatus') == 'true')
	{
		toggleUserOptions();
	}
	
	initTooltips();
	Ext.ux.Lightbox.register('a[rel^=lightbox]');
	
});		

function initTooltips()
{
	var divs = Ext.query('div');
	Ext.each(divs, function(obj) 
	{
		if (obj.getAttribute('connectId'))
		{
			var connectId = obj.getAttribute('connectId');
			var tt = new Ext.ToolTip(
			{        
			    title: obj.getAttribute('tooltipName'),
			    id: 'content-anchor-tip-' + connectId,
			    target: connectId,
			    anchor: 'left',
			    html: obj.innerHTML,
			    autoHide: true,
			    closable: true,
			    contentEl: obj.id
			});
		}
	});
	

}
	

function stopError() {
  return true;
}

window.onerror = stopError;

function scrollToTop()
{
	Ext.getBody().scrollTo('top', 0);

}

function scrollToBottom()
{
	Ext.getBody().scrollTo('bottom', 200);

}

function resetSearchForm() {
	document.getElementById('fldCategory').value = '';
	document.getElementById('fldCity').value = '';
//	document.getElementById('fldKeyword').value = '';
}

function activateTab(e) {

	if (e == 'tabProductenSearchContent') 
	{
	
		document.getElementById('tabProductenContent').className = 'tabcontent hidden';
		document.getElementById('tabContentProductSearch').className = 'tabcontent visible';
		document.getElementById('imgPleaseWait').style.backgroundImage = 'url(gfx/animations/progress_green_large.gif)';
	}

}

function fav(desc, url) {
if ( navigator.appName != 'Microsoft Internet Explorer' )
{ window.sidebar.addPanel(desc ,url,""); }
else { window.external.AddFavorite(url, desc); } }

function toggleDisplay(en) {
	var e = document.getElementById(en);
	if (e.className == 'hideBox') {
		e.className = 'showBox';
	} else {
		e.className = 'hideBox';
	}
}




var loginBoxStatus = true;
var winLogin;
function toggleLogin() 
{
 	loginBoxStatus = !loginBoxStatus;
     if (loginBoxStatus == true) 
     { 
     
		winLogin.hide();

     }	
     else
     {
     	if (!winLogin)
     	{
    		winLogin = showDialog('Inloggen', 'loginBox', {
                    text:'Inloggen',
                    handler: function()
                    {
                    	document.getElementById('frmLogin').submit();
                    }
                },{
                    text: 'Sluiten',
                    handler: function(){
                        win.winLogin();
                    }
                });
		}
		winLogin.show();
     }
}

var pricewatchBoxStatus = true;
var pricewatchBoxStatusInit = true;
function showDialog(title, div, buttons)
{
	 return new Ext.Window({
                applyTo: div,
                title: title,
                layout:'fit',
                width:500,
                y: 50,
                modal: true,
                closeAction: 'hide',
                plain: true,
                buttons: [buttons]
            });
}

var winPrice;
function togglePriceWatch(initOnReady)
{

	scrollToTop();
	
	if (!winPrice)
	{ 
		if (initOnReady)
		{
			winPrice = showDialog('Prijsalarm aangemaakt', 'alarmBox', {
                    text:'Sluiten',
                    handler: function()
                    {
				      	winPrice.hide();
                    }
                },{
                    text: 'Sluiten',
                    handler: function(){
                        winPrice.hide();
                    }
                });
		}
		else
		{
			winPrice = showDialog('Prijsalarm aanmaken', 'alarmBox', {
                    text:'Aanmaken',
                    handler: function()
                    {
                    	document.getElementById('frmPriceWatch').submit();
                    }
                },{
                    text: 'Sluiten',
                    handler: function(){
                        winPrice.hide();
                    }
                });
		}                
    }

 	 pricewatchBoxStatus = !pricewatchBoxStatus;
     if (pricewatchBoxStatus == true) 
     { 
      	winPrice.hide();
		
     }	
     else
     {
     
		winPrice.show();
		
		if (pricewatchBoxStatusInit == true)
		{
			var e= document.getElementById('idCaptcha').innerHTML = '<img src="gfx/cap.cfm" />';
			pricewatchBoxStatusInit = false;
		}



     }
}

 function toggleSearchOptions() {
 	searchBoxStatus = !searchBoxStatus;
     if (searchBoxStatus == true) 
     { 
     	document.getElementById('searchExpandIcon').src = 'gfx/icons/expand.png';

		Ext.get('searchOptions').syncFx().fadeOut().slideOut();

     }	
     else
     {
     

     	document.getElementById('searchExpandIcon').src = 'gfx/icons/collapse.png';

		Ext.get('searchOptions').syncFx().fadeIn().slideIn();

     }
}

function toggleUserOptions() 
{
	setCookie('searchUserBoxStatus', searchUserBoxStatus, 30);
 	searchUserBoxStatus = !searchUserBoxStatus;
	
     if (searchUserBoxStatus == true) 
     { 
     	document.getElementById('userOptionsExpandIcon').src = 'gfx/icons/expand.png';
		var e = document.getElementById('userOptionsBox');
		e.style.display = 'none';
     }	
     else
     {
     
     	document.getElementById('userOptionsExpandIcon').src = 'gfx/icons/collapse.png';
		var e = document.getElementById('userOptionsBox');
		e.style.display = 'block';
     }
}

function toggleOptions(e) {
	
	o = dojo.byId(e);
	if (!o.getAttribute('expanded')) 
	{
		o.setAttribute('expanded', false);
	}
     if (o.expanded == true) 
     { 
		o.expanded = false;
     	document.getElementById(e + 'Icon').src = 'gfx/icons/expand.png';
		var wipeOut = dojo.fx.wipeOut({node: e,duration: 300});
		var fadeOut = dojo.fadeOut({node: e,duration: 300});
		
		var ani = dojo.fx.combine([wipeOut, fadeOut]);
		ani.play();

     }	
     else
     {
		o.expanded = true;
     
     	document.getElementById(e + 'Icon').src = 'gfx/icons/collapse.png';
		var wipeIn = dojo.fx.wipeIn({node: e,duration: 300});
		var fadeIn = dojo.fadeIn({node: e,duration: 300});

		var ani = dojo.fx.combine([wipeIn, fadeIn]);
		ani.play();


     }
}

function deleteMonitor(o)
{
	if (confirm('Weet u zeker dat u deze product monitor wilt verwijderen ?'))
	{
		document.location.search = '?action=delete&id=' + o;
	}
}

function deleteFavorite(o)
{
	if (confirm('Weet u zeker dat u deze product favoriet wilt verwijderen ?'))
	{
		document.location.search = '?action=delete&id=' + o;
	}
}

function setFamilyFilter(o)
{
	document.location.search = '?action=familyfilter&set=' + o;
}


function setSpotLight(o)
{
	document.location.search = '?action=spotlight&set=' + o;
}

function resetClicks()
{
	document.location.search = '?action=resetclicks';
}

function cycleLayout(o)
{
	document.location.search = '?layout=' + o;
}

function doSearch()
{
	activateTab('tabProductenSearchContent');
}

function map(e) {
	toggleDisplay(e);		
	if (!clicked) {
		clicked = true;
		load();
	}
}

function setCookie(c_name, value, expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString() + "; path=/");
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}
