/**
 * @author Balint Zoltan
 */

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}

window.addEvent("domready",function(){
	Slimbox.scanPage();
	SearchForm.Init();
	SearchForm.initReset();
	RegistrationForm.Init();
	Tabber.Init();
	ProductFilter.Init();
	ConfirmBox.Init();
	InfoBox.scanPage();
	
	$$('.scroller.horizontal').filter(function(el){
		new TScroller(el,{ItemsPerScroll:4,ScrollSpeed:500,DisplayedItems:4,ItemDimension:160,PageInterval:2200});
	})
	$$('.scroller.vertical').filter(function(el){
		new TScroller(el,{ItemsPerScroll:9,DisplayedItems:9,MouseItemsPerScroll:5});
	})
	
});

// String Reverse extension
String.prototype.Reverse = function(){
	var retval = '';
	var len = this.length;
	while (len>0){
		retval+=this.substring(len-1,len);
		len--;
	}
	return retval;
}
// reversed email decoder
String.prototype.decodeMail = function(){
	var retval = this.Reverse();
	retval = retval.replace(/\]dot\[/gi,'.');
	retval = retval.replace(/\]at\[/i,'@');
	return retval;
}


// Registration Form fields
var RegistrationForm={};
RegistrationForm.Init = function(){
	$$('.toggler').filter(function(el){
		var toToggle = $('toggle_'+el.id);
		el.slider = new Fx.Slide(toToggle);
		if (!el.checked)
			el.slider.hide();
		el.addEvent('click',function(e){
			if (el.id=='rdoPF') $('reg_lbl_name').set('text','Nume si prenume:');
			else if (el.id=='rdoPJ') $('reg_lbl_name').set('text','Nume firma:');
			$$('.toggler').filter(function(el){
				if (el != this) {
					el.slider.hide();
				}
			});
			this.slider.show();
		});
	});
}

// Search form ajax filter
var SearchForm = {
	mainCategoryID : 0,
	subCategoryID : 0,
	brandID : 0,
	isReset : false
};
SearchForm.Data = {};

SearchForm.initReset = function(){
	$('search_reset').addEvent('click', function(){
		$('filter_currency').selectedIndex=0;
		$('filter_price_min').value='0';
		$('filter_price_max').value='0';
		$('filter_text').value='';
		showload = new Array('container_brand', 'container_sub_category', 'container_main_category');
		SearchForm.mainCategoryID = 0;
		SearchForm.subCategoryID = 0;
		SearchForm.brandID = 0;
		SearchForm.SendFilter(showload);
		SearchForm.isReset = true;
		return false;
	});
}

SearchForm.Init = function(){
	$('filter_main_category').addEvent('change',function(){
		showload = new Array('container_brand','container_sub_category');
		SearchForm.mainCategoryID = this.value;
		SearchForm.SendFilter(showload);
		//$('info').set('text',$('info').get('text')+' | maincat ');
	})
	$('filter_sub_category').addEvent('change',function(){
		showload = new Array('container_main_category','container_brand');
		SearchForm.subCategoryID = this.value;
		SearchForm.SendFilter(showload);
		//$('info').set('text',$('info').get('text')+' | subcat ');
	})
	$('filter_brand').addEvent('change',function(){
		showload = new Array('container_main_category','container_sub_category');
		SearchForm.brandID = this.value;
		SearchForm.SendFilter(showload);
		//$('info').set('text',$('info').get('text')+' | brand ');
	})
}

SearchForm.SendFilter = function(showload){
		//$('info').set('text',$('info').get('text')+' | INIT :: ');
		new Request.HTML({
			method: 'post',
			url: 'ajax_request.php',
			data: {
					'search_main_category_filter'	:SearchForm.mainCategoryID,
					'search_sub_category_filter'	:SearchForm.subCategoryID,
					'search_brand_filter'			:SearchForm.brandID,
					'context'						:'search_form'
			},
			onRequest: function() {
				//$('info').set('text',$('info').get('text')+' | sent');
				for (var i=0;i<showload.length;i++){
					$(showload[i]).addClass('loading');
					$(showload[i]).innerHTML='';
				}
			},
			update: $('search_filters'),
			onComplete: function(response) {
				for (var i=0;i<showload.length;i++){
					$(showload[i]).removeClass('loading');
				}
				//$('info').set('text',$('info').get('text')+' | loaded \r\n');
				SearchForm.Init();
			}
		}).send();	
}

// TABS
var MultiFilter = {
	activeLinks : 0
}
MultiFilter.Init = function(currentTab,type,mainId){
	if (!currentTab){
		$$('.multifilter input[type="checkbox"]').filter(function(el){
			el.removeAttribute('disabled');
		})
		return false;
	}
	var Ids;
	var ProdCount;
	var hash = window.location.hash;
	var req = new Request({
		method:'post',
		url: 'ajax_request.php',
		data: {
				'master_id'		:mainId,
				'id'			:currentTab.replace(/#tab_/,''),
				'is_main_tab'	:currentTab.match(/#tab_/)?false:true,
				'context'		:'multi_filter_tab_'+type
		},
		onRequest: function() {
			//alert('request sent');
		},
		onFailure: function(r){
			//alert(r);
		},
		onComplete: function(response) {
			//alert(response);
			var IDnCnt = response.split(';');
			Ids = IDnCnt[0].split(',');
			ProdCount = IDnCnt[1].split(',');
			var i=-1;
			$$('.multifilter a').filter(function(el){
//				alert(brandProdCount[i]);
				var checkbox = el.parentNode.getElementsByTagName('input')[0];
				var tmpUrl = el.href.split('#');
				tmpUrl = tmpUrl[0];
				if (!tmpUrl.match('oferta.html')) {
					el.href = tmpUrl + currentTab;
				}
				var pNID = el.parentNode.id.replace(/mf_/,'');
				var span = el.getElementsByTagName('span')[0];
				if (!in_array(pNID,Ids) && pNID!='0' && currentTab.match(/#tab_/)){
					el.addClass('inactive');
					el.onclick = function(){
						return false;
					}
					if (span) span.innerHTML = '0';
					checkbox.setAttribute('disabled','disabled');
					checkbox.checked = false;
				}else{
					el.removeClass('inactive');
					if (span) span.innerHTML = ProdCount[i];
					checkbox.removeAttribute('disabled');
					checkbox.checked = checkbox.origChecked;
					el.onclick = function(){
						return true;
					}
					i++;
				}
			});
			if(currentTab.match(/#tab_/)){
				var el = $('mf_0').getElementsByTagName('a')[0];
				var checkbox = el.parentNode.getElementsByTagName('input')[0];
				el.addClass('inactive');
				el.onclick = function(){
					return false;
				}
				checkbox.setAttribute('disabled','disabled');
				checkbox.checked = false;
			}
		}
	}).send();
}



var Tabber = {
	maxWidth 	: 675,
	tabMargin	: 1,
	tabPadding	: 20,
	tabBorder	: 2
};

Tabber.Adjust = function(Tabs,from,to,width){
	var totalWidth=0;
	if (1==1)
	for (var i=from;i<to;i++){
		var currentWidth = Tabs[i].offsetWidth;
		var widthToSet = currentWidth+width-(this.tabMargin+this.tabPadding+this.tabBorder);
	
		Tabs[i].setStyle('width',widthToSet);
		totalWidth+=Tabs[i].offsetWidth;
	}
	var gap = this.maxWidth-(totalWidth+(to-from)*this.tabMargin);
	if (gap!=0){
		Tabs[from].setStyle('width',Tabs[from].getStyle('width').toInt()+gap);
	}
}

Tabber.Init = function(){
	var i=0;
	var lastRowIndex=0;
	var currentWidth=0;
	var currentTab = self.document.location.hash.substring(1);
	var type = $('mf_brand')?'brand':'category';
	var useAjax = $('mf_'+type)?true:false;
	var mainId = useAjax?$('mf_'+type).getElementsByTagName('fieldset')[0].id:null;
	if (useAjax) {
		mainId = mainId.split('ms_');
		mainId = mainId[1];
	}
	
	if (currentTab!='')
		if (document.getElementById(currentTab) && useAjax)
			MultiFilter.Init('#'+currentTab,type,mainId);
	$$('.tabs').filter(function(tabGroups){
		// filter tab handles
		tabGroups.Tabs = new Array();
		tabGroups.currentTab = null;
		
		tabGroups.getElements('a').filter(function(el){
			tabGroups.Tabs[i] = el;
			el.controlContent = $(el.rel);
			// if handle has element to control
			if (el.controlContent!==null){
				if (el.hasClass('active') || el.rel==currentTab){
					tabGroups.currentTab = el;
					if (!el.hasClass('active'))
						el.addClass('active');
					el.controlContent.setStyle('display','block');
				}else{
					el.controlContent.setStyle('display','none');
				}
			}
			
			// adjust tab width
			if (currentWidth+el.offsetWidth>Tabber.maxWidth){
				var widthToAdd = ((Tabber.maxWidth-currentWidth)/(i-lastRowIndex)).toInt();
				Tabber.Adjust(tabGroups.Tabs,lastRowIndex,i,widthToAdd)
				currentWidth = el.offsetWidth;
				lastRowIndex = i;
			}else{
				currentWidth+=el.offsetWidth;
			} 

			// handle click
			el.addEvent('click',function(e){
				if (tabGroups.currentTab && (this.controlContent && this!=tabGroups.currentTab)) {
					this.controlContent.id = this.controlContent.id+'.fake';
					this.controlContent.setStyle('display','block');
					this.addClass('active');

					tabGroups.currentTab.removeClass('active');
					tabGroups.currentTab.controlContent.setStyle('display','none');
					tabGroups.currentTab = this;
				}
				if (useAjax)
					MultiFilter.Init('#'+this.rel,type,mainId)
				window.location.hash=this.rel;
				return false;
			}); // end click
			++i;
		}); // end filter EL

		// set default active tab		
		if (!tabGroups.currentTab){
			tabGroups.currentTab = tabGroups.Tabs[0];
			tabGroups.currentTab.controlContent.setStyle('display','block');
			tabGroups.currentTab.addClass('active');
		}
		// adjust last row tab width
		var widthToAdd = ((Tabber.maxWidth-currentWidth)/(i-lastRowIndex)).toInt();
		if (lastRowIndex > 0 && (i-lastRowIndex>1)) {
			Tabber.Adjust(tabGroups.Tabs, lastRowIndex, i, widthToAdd)
		}
		window.scrollTo(0,0);
	}); // end filter tabgroup
	MultiFilter.Init()
}




// Filtru produse

var ProductFilter = {};
ProductFilter.Init = function(){
	$$('form ul.alphalist.categories li input[type="checkbox"]').filter(function(el){
		el.origChecked = el.getAttribute('checked');
		el.addEvent('click',function(){
			var link = this.parentNode.getElementsByTagName('input')[1];
			window.location = link.value;
		});
	})
}

// adauga mesaj de confirmare stergeri comenzi

var ConfirmBox = {}

ConfirmBox.Init = function(){
	$$('.del').filter(function(el){
		el.addEvent('click',function(){
			return confirm('Sigur vreti sa stergeti?');
		})
	})
}

// info-box
var InfoBox = {
	cookie:null,
	cookieName:'itp-infobox',
	cookieDuration:5,
	hide:function(el,onInit){
		if (!onInit){
			InfoBox.setCookie(el.scope);
		}
		el.parentNode.removeChild(el);
	},
	show:function(el){
		el.setStyle('display','block');
	},
	setCookie:function(scope){
		InfoBox.cookie.set(scope,'1');
		InfoBox.cookie.save();
	},
	scanPage:function(){
		InfoBox.cookie = new Hash.Cookie(InfoBox.cookieName,{duration:InfoBox.cookieDuration, autoSave: false, path:'/'});
		$$('.info').filter(function(el){
			var closeButton = el.getFirst('a');
			el.closeButton = closeButton;
			el.scope = el.closeButton.get('rel');
			
			el.closeButton.addEvent('click',function(e){
				InfoBox.hide(el)
				return false;
			})
			if (InfoBox.cookie.get(el.scope)){
				InfoBox.hide(el,true);
			}else{
				InfoBox.show(el);
			}
		})
	}
}

function printProduct(id){
	window.open('print/'+id, 'print', 'width=720,height=560,scrollbars=1');
}
