/*
@author: Mohsen Taleb <http://www.mohsentaleb.com>
*/

var SamService={
	
	start:function(){
		SamService.initSearchBox();
		SamService.initMenu();
	},
	
	initMenu:function() {
		SamService.navMenuContainer = $('nav_menu');
		SamService.navMenuParents = $('menu');
		SamService.navMenuMorph = new Fx.Styles(SamService.navMenuParents, {duration:200, wait:false, unit: 'px'});
		SamService.subMenuIsShown = false;
		SamService.menuRefs = [];
		var topLevels = SamService.navMenuParents.getElements("li.parent a[class=item]");
		var focusOnMenu = false;
		
		SamService.navMenuContainer.addEvent('mouseenter', function(){
			focusOnMenu = true;
		});
		SamService.navMenuContainer.addEvent('mouseleave', function(){
			focusOnMenu = false;
			(function(){
				  if (!focusOnMenu) SamService.hideSubMenu()
					  }).delay(2000);
		});
		topLevels.each(function(el, i){

				var listItem = el.getParent();
				var subMenu = listItem.getElement('ul');

				var _1 = [];
				_1["ref"] = el;
				_1["hasSub"] = ($E('ul.sub', listItem) != null) ? true : false;
				if (subMenu != null) {
					_1["subMenuRef"] = subMenu;
					_1["subMenuEffect"] = new Fx.Styles(subMenu, {duration:200, wait:false, unit: 'px'});
				}
				
				SamService.menuRefs.push(_1);
				
				el.addEvent('click', function(e){
					e = new Event(e).stop();
					if (SamService.subMenuIsShown) {
						 if (SamService.menuRefs[i].hasSub != true) {
							SamService.hideSubMenu(i);
							SamService.subMenuIsShown = false;
						 }
						 else {
							SamService.showSubMenu(i);
							SamService.subMenuIsShown = true;							 
						 }
					}
					else {
						if (SamService.menuRefs[i].hasSub != true) {
							SamService.hideSubMenu(i);
							SamService.subMenuIsShown = false;
						 }
						 else {
							SamService.showSubMenu(i);
							SamService.subMenuIsShown = true;							 
						 }
					}
				});
			}
		);

	},
	showSubMenu:function(menuItem) {
		SamService.navMenuMorph.start({'top': 0,'right': 0});
		SamService.menuRefs.each(function(array, i){
				if (i != menuItem) {
					if (array["subMenuRef"] != null ) array["subMenuRef"].setStyles({'right':40, 'display':'none'});
					array["ref"].addClass('inactive');
					array["ref"].removeClass('active');
				}
				else {
					if (array["subMenuRef"] != null ) {
						array["subMenuRef"].setStyle('display', 'block');
						array["subMenuEffect"].start({'right':0, 'opacity':100});	
					}
					array["ref"].addClass('active');
					array["ref"].removeClass('inactive');
				}
		});
	},
	hideSubMenu:function(menuItem) {
		SamService.navMenuMorph.start({'top': 20,'right': 20});
		SamService.menuRefs.each(function(array, i){
				if (array["subMenuRef"] != null ) array["subMenuRef"].setStyles({'right':40, 'display':'none'});
				array["ref"].removeClass('inactive').removeClass('active');
				if (i == menuItem) array["ref"].addClass('active');
		});		
	},
				

	initSearchBox:function() {
		SamService.searchBox = $$('input[id$=txtSearch]');

		var defaultString = 'جستجو در سام سرویس';
		SamService.searchBox.value = defaultString;
		
		SamService.searchBox.addEvent('focus', function(){
			this.addClass('focus');
			this.value =  (this.value == defaultString) ? (this.value = '') : this.value;
		});
		SamService.searchBox.addEvent('blur', function(){
			this.removeClass('focus');												
			this.value =  (this.value == '') ? (this.value = defaultString) : this.value;
		});

	},
	convertToFarsi: function(Num){
        var Num = new String(Num);
		var str = '';
        for(var i=0; i< Num.length; i++){
                if(Num[i] >= 0 && Num[i] <= 9){
                        str += String.fromCharCode(Num.charCodeAt(i) + 1728);
                }
                else
                        str += String.fromCharCode(Num.charCodeAt(i));
        }
        return str;
	},
	sncInit:function() {

		SamService.snc = new customFormElements({scope: 'search_n_compare'});
		
		var productsBoxes = $$('.product_box');
		var compareBtn = $$('input[id$=ibCompare]');
		var resetButton = $('reset_btn');

		SamService.checkedProducts = 0;
		SamService.totalProducts = $('total_products');
		SamService.totalProducts.setText(SamService.convertToFarsi(productsBoxes.length)+" محصول از این دسته موجود می باشد");
		
/*		compareBtn.addEvent('click', function(){
			if (SamService.checkedProducts < 2 || SamService.checkedProducts > 3) {
				alert('برای مقایسه می بایست حداقل ۲ و حداکثر ۳ محصول را انتخاب نمایید');
				return false;
			}
			else {
				return true;	
			}
		});
*/
		if (resetButton) resetButton.addEvent('click', function(){SamService.snc.cbResetAll()});
		

		$ES('div.product_box input').addEvent('change', function(){
			if (this.checked == true) SamService.checkedProducts++;
			else SamService.checkedProducts--;
		});
		
		SamService.products = [];
		productsBoxes.each(function(product, index){
			var _1 = [];
			_1["ref"] = product;
			_1["fx"] = new Fx.Style(product, 'opacity', {duration:500, wait:false});
			_1["shown"] = true;
			_1["chbox"] = product.getElement('input');
			_2=product.getElement('span').getText().split(',');
			for (var i = 0; i < _2.length; i++) {
				_2[i] = parseInt(_2[i]	);
			}
			SamService.products.push(_1);
			SamService.products[index].specs = _2;
		});
		
		SamService.snc.cbGroupSelectorInit();
	},
	
	sncRefreshView: function(chbArray) {
		var i,j,temp, total=0;
			for (i = 0; i < SamService.products.length; i++) {
				for (j = 0; j < chbArray.length; j++) {
					if (SamService.products[i].specs.indexOf(chbArray[j].value) != -1) {temp = true;}
					else {
						if(chbArray[j].selected) {temp = false; break;}
						else {temp = true;}
					}
				}

				if (temp == SamService.products[i].shown ) {if(temp == true) total++; continue;}
				SamService.products[i].shown = temp;
				
				if (SamService.products[i].shown) {
					total++;
					SamService.products[i].ref.setStyle('display', 'block');
					SamService.products[i].fx.start(0,1);
				}
				else {
					if (SamService.products[i].chbox.checked) {
						SamService.products[i].chbox.checked = false;
						SamService.checkedProducts--;
					}
					SamService.products[i].fx.start(1,0).chain(function(){
					SamService.products[this].ref.setStyle('display', 'none')}.bind(i));
					
				}
			}
			SamService.totalProducts.empty().setText(SamService.convertToFarsi(total)+" محصول با توجه به شرایط انتخاب شده");
	},
	
	initSend2Friend: function() {
		var sendtoToggler = $('sendto_toggler');
		var formDivSlide = new Fx.Slide('send2friend').hide();
		sendtoToggler.addEvent('click', function(e){
			e = new Event(e);
			formDivSlide.toggle();
			e.stop();
		});
	},
	
	initSend2FriendAGAIN: function() {
		var sendtoToggler = $('sendto_toggler');
		var formDivSlide = new Fx.Slide('send2friend');
		sendtoToggler.addEvent('click', function(e){
			e = new Event(e);
			formDivSlide.toggle();
			e.stop();
		});
	},
	
	openPopup: function(page,w,h) {
	    window.open(page, '_blank', 'width='+w+',height='+h+',scrollbars=no,status=no');
	},
	
	Popup: function(page){
		window.open(page, '_blank','scrollbars=no,status=no');
	},
	
	initFAQ: function() {
		$$("a.question").each(function(listItem){
			var answer = listItem.getNext();
			listItem.addEvent('click', function(e){
				e = new Event(e).stop();
				var toggleValue = (answer.getStyle('display') == 'none') ? 'block' : 'none' ;
				answer.setStyle('display', toggleValue);
			});
		});
	},

	resetCheckBoxes: function() {
		$$('input[type=checkbox]').each(function(checkbox){checkbox.checked=false});
	}
};

window.addEvent('domready', function() {
	SamService.start();
});
document.write('<style type="text/css" media="screen">ul.sub{display: none}</style>');