// number format, equivalent php
function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
    //alert('here');
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

function filebrowser_preloader() {
	el=$('filebrowser_preloader').style;
	el.display=(el.display == 'block')?'none':'block';

}



function addSearchEngine($cesta,$title,$desc) {
  if ((typeof window.sidebar == "object") &&
      (typeof window.sidebar.addSearchEngine == "function")) {

    window.sidebar.addSearchEngine(
      $cesta+"/search-ff.src",
      //$cesta+"/articles/search_addon",
      $cesta+"/css/fastest/icons/favicon.ico",
      $title,
      $desc);

  } else
    alert("Váš prohlížeč nepodporuje tuto funkci. Zkuste Mozillu.");

}

// tooltips shop detail table
function detail_table_tooltips(){
window.addEvent('domready', function(){
	var Tips_help = new Tips($$('.detail_table_tip'),{
			showDelay: 400,
			hideDelay: 400,
			className: 'detail_table_tip',
			offsets: {'x': -170, 'y': -30},
			fixed: true
	}); 
});
}

// tooltips
function footer_tooltips(){
window.addEvent('domready', function(){
		var Tips_help = new Tips($$('.tip_win'),{
			showDelay: 400,
			hideDelay: 8500,
			className: 'tip_win',
			offsets: {'x': -149, 'y': -80},
			fixed: true
	
		});
		new SmoothScroll({
			 links: '.scroll_moo',
			duration:700 
		},window);
	
});
}
// skryvani zapomenuteho hesla
function hide_lost_password(){
$('forgot_passwords_form').fade('hide');
$('forgot_password_link').addEvent('click', function(e) {
	new Event(e).stop();
	$('logins_form').fade(0);
	$('forgot_passwords_form').fade(1);
});

$('login_link').addEvent('click', function(e) {
	new Event(e).stop();
	$('forgot_passwords_form').fade(0);
	$('logins_form').fade(1);
});
}

// doporuceni domwin
function doporuceni_win(title){
	$('doporuceni_link').addEvent('click',function(e){
	new Event(e).stop();
	domwin.newWindow({
		id			: 'doporuceni_win',
		sizes		: [500,220],
		scrollbars	: false,
		defined_lang: ['cz'],
		languages	: false,
		title		: title,
		ajax_url	: '/doporucenis/',
		closeConfirm: false,
		max_minBtn	: false,
		modal_close	: true
	});
	});
}

// minimalni delka search pole
function min_delka_search(id,text,alert_text,lang){
	
	if (($(id).value == text) || ($(id).value.length < 3))
		alert(alert_text);
	else
		window.location.href =  lang + '/produkty/?search_fulltext=' + id.value;
			
}



function getHighestIndex(){				
		var allElems = document.getElementsByTagName?document.getElementsByTagName("*"): document.all; 
		var maxZIndex = 0;
		for(var i=0;i<allElems.length;i++) {
			var elem = allElems[i];
			var cStyle = null;
			if (elem.currentStyle) {cStyle = elem.currentStyle;
			} else if (document.defaultView && document.defaultView.getComputedStyle){
				cStyle = document.defaultView.getComputedStyle(elem,"");
			}
			var sNum;
			if (cStyle) {
				sNum = Number(cStyle.zIndex);
			} else {
				sNum = Number(elem.style.zIndex);
			}
			if (!isNaN(sNum)) {
				maxZIndex = Math.max(maxZIndex,sNum);
			}
		}
		return maxZIndex;
} 

Element.implement({
	inputLimit: function(){
		if (this.hasClass('float')){
			this.addEvent('keypress',function(e){
				var event = new Event(e); 
				var allow_key = ['1','2','3','4','5','6','7','8','9','0',',','backspace','left','right','tab','f5'];	
				if (allow_key.indexOf(event.key) != -1) 
					return true; 
				else 
					return false;			
			});
		} else if (this.hasClass('integer')){
			this.addEvent('keypress',function(e){
				var event = new Event(e); 
				var allow_key = ['1','2','3','4','5','6','7','8','9','0','backspace','left','right','tab','f5'];	
				if (allow_key.indexOf(event.key) != -1) 
					return true; 
				else 
					return false;			
			});
		}
	},
	
	ajaxLoad: function(url, children){
		var empty_value = '--- Zvolte hodnotu ---'
		this.addEvent('change', function(){
			new Request.JSON({
				url: url + this.value,
				onComplete: (function(json){
					children.each(function(obj){
						$(obj).empty();
						new Element('option', {title:empty_value, value:''}).setHTML(empty_value).inject($(obj));
					});
					child = children[0];
					$each(json, function(value, id){
						new Element('option', {title:value, value:id}).setHTML(value).inject($(child));
					}, this);
				}).bind(this)
			}).send();
		});
	},
	
	getOptionText: function(){
		return this.options[this.selectedIndex].getHTML();
	}
});
String.implement({
	camelCase2: function(){
		return (this.replace(/_\S/g, function(match){
			return match.charAt(1).toUpperCase();
		})).capitalize();
	}
});

function tisk(){
window.print();
return false;
}

function button_preloader(id){
		id.addClass('button_preloader');
		id.setProperty('disabled');
}

function button_preloader_disable(id){
		id.removeClass('button_preloader');
		id.removeProperty('disabled');
}

 function html_entity_decode (string, quote_style) {
        var hash_map = {}, symbol = '', tmp_str = '', entity = '';
        tmp_str = string.toString();
        
        if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
            return false;
        }
    
        delete(hash_map['&']);
        hash_map['&'] = '&amp;';
    
        for (symbol in hash_map) {
            entity = hash_map[symbol];
            tmp_str = tmp_str.split(entity).join(symbol);
        }
        tmp_str = tmp_str.split('&#039;').join("'");
        
        return tmp_str;
    }


// zmena pisma ve clankach
function init_font_changer(){
	Cookie.get("fontType");
	switchFont(Cookie.get("fontType"));

	if ($('switch_f1'))$('switch_f1').addEvent('click',function(e){new Event(e).stop();switchFont(1);setFontSize(1)})
	if ($('switch_f2'))$('switch_f2').addEvent('click',function(e){new Event(e).stop();switchFont(2);setFontSize(2)})
	if ($('switch_f3'))$('switch_f3').addEvent('click',function(e){new Event(e).stop();switchFont(3);setFontSize(3)})



	function switchFont(typ)
	{
		if (typ==1){
		
		$('obal').getElements('.article_text').removeClass('large_font').addClass('small_font');
		$('obal').getElements('.article_anotace').removeClass('large_font').addClass('small_font');				
		$('obal').getElements('.f1').addClass('active');				
		$('obal').getElements('.f2').removeClass('active');				
		$('obal').getElements('.f3').removeClass('active');				
		}
		
		if (typ==2){
		$('obal').getElements('.article_text').removeClass('small_font').removeClass('large_font');				
		$('obal').getElements('.article_anotace').removeClass('small_font').removeClass('large_font');				
		$('obal').getElements('.f1').removeClass('active');				
		$('obal').getElements('.f2').addClass('active');				
		$('obal').getElements('.f3').removeClass('active');				
		}

		if (typ==3){
		$('obal').getElements('.article_text').removeClass('small_font').addClass('large_font');
		$('obal').getElements('.article_anotace').removeClass('small_font').addClass('large_font');				
		$('obal').getElements('.f1').removeClass('active');				
		$('obal').getElements('.f2').removeClass('active');				
		$('obal').getElements('.f3').addClass('active');				
		}
		

	  }
	function setFontSize(typ){
		Cookie.remove('fontType');
		var myCookie  =  Cookie.set('fontType', typ,{path: '/'});

	}
}


/*
* detail produktu
*/
function detail_product(lang_nakupni_kosik){

	$('product_detail_table_params').getElements('table').each(function(item){
		stripeTable(item);
	});


	function stripeTable(t) {
	   var i, odd = true;
	   for (i=0; i<t.rows.length; i++) {
		  t.rows[i].className += odd ? ' t_odd' : ' t_even';
		  odd = !odd;
		  }
	   }

		
		
		// fotogalerie
		if ( $('karta_produktu').getElement('.shop_detail_img_list')){
			width_inner = $('karta_produktu').getElement('.overflow').getSize().x.toInt();
			width_obal 	= $('karta_produktu').getElement('.shop_detail_img_list_inner').getSize().x.toInt();
			step = $('karta_produktu').getElement('.overflow').getElement('a').getSize().x.toInt();
			$('img_prev').addEvent('mousedown',function(){
				var to_move = $('karta_produktu').getElement('.overflow');
				kam = to_move.getStyle('left').toInt()+step;
				to_move.morph({left: (kam>0)?0:kam,transition: 'bounce:out'});	
			});
			$('img_next').addEvent('mousedown',function(){
				var to_move = $('karta_produktu').getElement('.overflow');
				var rozdil = width_inner - width_obal;
				if (rozdil > 0){
					now_left = to_move.getStyle('left').toInt();
					if(rozdil + now_left - step >= 0){
						kam = now_left-step;
					} else {
						kam = now_left-step - (rozdil + now_left - step) -1;
					}
					to_move.morph({left: kam,transition: 'bounce:out'});
				}	
			});
		}

		// relaod varianty
		if ($('VariantaId'))
			$('VariantaId').addEvent('change',function(e){
				$('product_detail_table_params').getElement('table').fade(0);
				new Request.HTML({
					update: 'product_detail_table_params',
					url: '/nacteni_varianty/' + this.value,
					onComplete: (function(e){
						$('KosikProductId').value = this.value;
					}).bind(this)
				}).send();
			})
			
		// vlozeni do kosiku
		$('action_add_to_basket').addEvent('click', function(e){
			new Event(e).stop();
			domwin.newWindow({
				id			: 'basket_domwin',
				sizes		: [700,820],
				scrollbars	: true,
				languages	: false,
				title		: lang_nakupni_kosik,
				ajax_url	: this.getParent('form').getProperty('action'),
				closeConfirm: false,
				max_minBtn	: false,
				modal_close	: true,
				post_data	: {
					'data[Kosik][method]'		: 'add',
					'data[Kosik][product_id]'	: $('KosikProductId').value,
					'data[Kosik][count]'		: $('KosikProductCount').value
				}
			}); 
		});
}


/*change language*/
function change_language(mena_link){
	if ($('seznam_men'))
		$('seznam_men').getElements('.change_language').addEvent('click',function(e){
			new Event(e).stop();
			var str = this.id;
			var mena_id = str.substr(4);
			window.location = mena_link+mena_id;
		});
}


/*client login*/
function client_login(lang_email,lang_heslo){

	if($('client_zapomenute_heslo'))
		$('client_zapomenute_heslo').addEvent('click',function(e){
			new Event(e).stop();
			domwin.newWindow({
				id			: 'client_zapomenute_heslo_domwin',
				sizes		: [600,280],
				scrollbars	: true,
				languages	: false,
				title		: this.getProperty('title'),
				ajax_url	: this.getProperty('href'),
				closeConfirm: false,
				max_minBtn	: false,
				modal_close	: false
			}); 
		})


	if ($('client_change_password'))
		$('client_change_password').addEvent('click',function(e){
			new Event(e).stop();
			domwin.newWindow({
				id			: 'client_change_pass_domwin',
				sizes		: [600,280],
				scrollbars	: true,
				languages	: false,
				title		: this.getProperty('title'),
				ajax_url	: this.getProperty('href'),
				closeConfirm: false,
				max_minBtn	: false,
				modal_close	: false
			}); 
		});

	if ($('client_change_data'))
		$('client_change_data').addEvent('click',function(e){
			new Event(e).stop();
			domwin.newWindow({
				id			: 'client_change_data_domwin',
				sizes		: [700,375],
				scrollbars	: true,
				languages	: false,
				title		: this.getProperty('title'),
				ajax_url	: this.getProperty('href'),
				closeConfirm: false,
				max_minBtn	: false,
				modal_close	: false
			}); 
		});

	if ($('client_login_do'))
		$('client_login_do').addEvent('click',function(e){
			new Event(e).stop();
			new Request.JSON({
				url: $('shop_box_login_form').getProperty('action'),
				onComplete: function(json){
					if (json){
						if (json.result === true){
							window.location = window.location;
						} else {
							alert(json.message);
						}
					} else {
						alert('Chyba aplikace');
					}
				}
			}).send($('shop_box_login_form'))
		});

	if($('LoginClientHeslo'))
		$('LoginClientHeslo').addEvents({
			'focus': function(){
				if (this.value == lang_heslo){
					this.value = '';
					this.setProperty('type','password');
				}
			},
			'blur': function(){
				if (this.value == ''){
					this.value = lang_heslo;
					this.setProperty('type','text');
				}
			}
		});
	if($('LoginClientEmail'))
		$('LoginClientEmail').addEvents({
			'focus': function(){
				if (this.value == lang_email){
					this.value = '';
				}
			},
			'blur': function(){
				if (this.value == ''){
					this.value = lang_email;
				}
			}
		});


	if($('client_registrace'))
		$('client_registrace').addEvent('click',function(e){
			new Event(e).stop();
			domwin.newWindow({
				id			: 'client_registrace_domwin',
				sizes		: [700,330],
				scrollbars	: true,
				languages	: false,
				title		: this.getProperty('title'),
				ajax_url	: this.getProperty('href'),
				closeConfirm: false,
				max_minBtn	: false,
				modal_close	: false
			}); 
		})	
}


/*click refresh*/
function click_refresh(id){
	new Request.HTML({
		url:$('refresh').getProperty('href'),
		update:"product_list",
		onComplete: function(){
			document.ajax_history.start_up();
		}
	}).send()
};


/*products list items*/

function products_items(vyrobce_path,lang_nakupni_kosik,lang_vyber_varianty,lang_vyber_varianty_question,lang_vlozit_do_kosiku,lang_varianta,lang_zrusit){
	$('ShopPocetNaStranku').addEvent('change',function(){
		new Request.JSON({
			url: '/'+vyrobce_path+'/change_pocet/' + this.value,
			onComplete: function(json){
				if (json){
					if (json.result === true){
						click_refresh();
					} else {
						alert(json.message);
					}
				} else {
					alert('Chyba aplikace');
				}
			}
		}).send()
		
	})

	
	

	
	$('product_list').getElements('.item_add_kosik_form').addEvent('submit',function(e){
		new Event(e).stop();
		var varianty = this.getElement('.varianty');
		if (varianty){
			var main = new Element('div',{'class':'kosik_varianta'})
				.inject($('addon'))
				.setHTML('<h2>'+lang_vyber_varianty+'</h2><p>'+lang_vyber_varianty_question+'</p><p class="select_div"><label>'+lang_varianta+'</label><select></select><br/></p><div class="buttons"><input type="button" value="'+lang_vlozit_do_kosiku+'" class="button add"/><input type="button" value="'+lang_zrusit+'" class="button cancel"/></div>');
			var select = main.getElement('.select_div').getElement('select');
			$each(JSON.decode(varianty.value), function(caption, id){
				new Element('option',{title:caption, value:id}).setHTML(caption).inject(select);
			});


			var scroll_x = window.getScroll().y;
			$(document.html).setStyle('overflow-y','hidden');
			$(document.html).setStyle('overflow-x','hidden');
			$(document.body).setStyle('overflow-y','hidden');
			$(document.body).setStyle('overflow-x','hidden');
			window.scroll(0,scroll_x);
			
			var window_size = window.getSize(),x,y;
			domwin_size = main.getSize();
			x = (window_size.x/2 - domwin_size.x / 2);
			y = (window_size.y/2 - domwin_size.y / 2) + window.getScroll().y;
			main.setStyles({
				left: (x>10)?x:10,
				top	: (y>10)?y:10,
				position: 'absolute',
				'z-index':900
			});
			
			domwin_modal = new Element('div').addClass('domwin_modal').inject(main,'before')
				.setStyles({width:window_size.x,height:window_size.y, top: window.getScroll().y, opacity:0.1,"z-index":899,background:'#000000'})
			
			
			var cancelButton =  main.getElement('.cancel');
			if (cancelButton)
				cancelButton.addEvent('click',function(e){
					new Event(e).stop();
					main.dispose();
					domwin_modal.dispose();
					$(document.body).removeProperty('style');
					$(document.html).removeProperty('style');
					$(document.body).setProperty('style',' ');
					$(document.html).setProperty('style',' ');
					//START CHROME FIX - show scroller
					window.scroll(0,window.getScroll().y-1);
					//END CHROME FIX 
				});

			var addButton =  main.getElement('.add');
			if (addButton)
				addButton.addEvent('click',(function(e){
					new Event(e).stop();
					domwin.newWindow({
						id			: 'basket_domwin',
						sizes		: [700,820],
						scrollbars	: true,
						languages	: false,
						title		: lang_nakupni_kosik,
						ajax_url	: this.getProperty('action'),
						closeConfirm: false,
						max_minBtn	: false,
						modal_close	: true,
						post_data	: {
							'data[Kosik][method]'		: 'add',
							'data[Kosik][product_id]'	: select.value,
							'data[Kosik][count]'		: 1
						}
					}); 
					main.dispose();
					domwin_modal.dispose();
					$(document.body).removeProperty('style');
					$(document.html).removeProperty('style');
					$(document.body).setProperty('style',' ');
					$(document.html).setProperty('style',' ');
					//START CHROME FIX - show scroller
					window.scroll(0,window.getScroll().y-1);
					//END CHROME FIX 
				}).bind(this));

			
			
		} else {
			domwin.newWindow({
				id			: 'basket_domwin',
				sizes		: [700,820],
				scrollbars	: true,
				languages	: false,
				title		: lang_nakupni_kosik,
				ajax_url	: this.getProperty('action'),
				closeConfirm: false,
				max_minBtn	: false,
				modal_close	: true,
				post_data	: {
					'data[Kosik][method]'		: 'add',
					'data[Kosik][product_id]'	: this.getElement('.product_id').value,
					'data[Kosik][count]'		: 1
				}
			}); 
		}
	})
} 


/* newsletter element */
function newsletter_element(){
/*
$('news_reg_link').addEvent('click', function(e) {
	new Event(e).stop();
	$('reg_news').fade(1);
	$('unreg_news').fade(0);
});
$('news_cancel_link').addEvent('click', function(e) {
	new Event(e).stop();
	$('reg_news').fade(0);
	$('unreg_news').fade(1);
});
$('unreg_news').fade('hide');

*/
$('news_reg').addEvent('click',function(e){
		new Event(e).stop();
		valid_result = validation.valideForm('news_registration_form');
		if (valid_result == true){
			button_preloader($('news_reg'));
			new Request.JSON({
				url:$('news_registration_form').action,		
				onComplete:function(){
//					window.location = '/nabidka-odeslana/';
					alert('Váš email byl zaregistrován');
					$('news_reg').removeProperty('disabled');
					$('NewsletterName').removeClass('valid');
					$('NewsletterEmail').removeClass('valid');
					$('NewsletterName').addClass('require');
					$('NewsletterEmail').addClass('require');
					$('news_reg').removeClass('button_preloader');
					$('news_registration_form').getElements('.empty').each(function(item){item.value='';});
				}
			}).post($('news_registration_form'));
		} else {
			var error_message = new MyAlert(valid_result);
		}
});
	
	validation.define('news_registration_form',{
		'NewsletterName': {
			'testReq': {'condition':'not_empty','err_message':'Musíte vyplnit Vaše jméno'}
		},
		'NewsletterEmail': {
			'testReq': {'condition':'email','err_message':'Musíte vyplnit Váš email'}
		}
	
		
	});
	validation.generate('news_registration_form',false);
	
	/*
$('news_unreg').addEvent('click',function(e){
		new Event(e).stop();
		valid_result = validation.valideForm('news_unregistration_form');
		if (valid_result == true){
			button_preloader($('news_unreg'));
			new Request.JSON({
				url:$('news_unregistration_form').action,		
				onComplete:function(json){
						if (json.result == false)
							alert('Váš email nebyl nalezen');
						if (json.result == true)
							alert('Váš email byl odregistrován');
							
					$('news_unreg').removeProperty('disabled');
					$('NewsletterDeleteEmail').removeClass('valid');
					$('NewsletterDeleteEmail').addClass('require');
					$('NewsletterDeleteEmail').focus();
					$('news_unreg').removeClass('button_preloader');
					$('news_unregistration_form').getElements('.empty').each(function(item){item.value='';});
				}
			}).post($('news_unregistration_form'));
		} else {
			var error_message = new MyAlert();
			error_message.show(valid_result)
		}
});	
	validation.define('news_unregistration_form',{
		'NewsletterDeleteEmail': {
			'testReq': {'condition':'email','err_message':'Musíte vyplnit Váš email'}
		}
	
		
	});
	validation.generate('news_unregistration_form',false);*/

}


/*shop category*/
function shop_category(ul){
		$(ul).getElements('span').addEvent('click', function(e){
			new Event(e).stop();
			ul = this.getParent('li').getElement('ul');
			if (ul){
				if (ul.hasClass('none')){
					this.removeClass('close');
					this.addClass('open');
					ul.removeClass('none');
				} else {
					ul.addClass('none');
					this.addClass('close');
					this.removeClass('open');
				}
			}
		});
}

/*vstoupit do kosiku*/	
function enter_kosik(){
	$('enter_into_kosik').addEvent('click', function(e){
		new Event(e).stop();
		domwin.newWindow({
			id			: 'basket_domwin',
			sizes		: [900,820],
			scrollbars	: true,
			languages	: false,
			title		: 'Nakupni kosik',
			ajax_url	: this.getProperty('href'),
			closeConfirm: false,
			max_minBtn	: false,
			modal_close	: true
		}); 
	});
}
