// JavaScript Document
var debug=true;

//tarayıcının ne olduğu bulunuyor
var BROWSER=null;
var IE6=null;
var IE7=null;
var agent=navigator.userAgent;
if(agent.indexOf("MSIE")>-1){
	BROWSER="explorer";
	var v=parseInt(agent.substr(agent.indexOf("MSIE")+5,1));
	if(v<7){
		IE6=true;
	}else{
		IE7=true;
	}
}else if(agent.indexOf("Firefox")>-1){
	BROWSER="firefox"
}else if(agent.indexOf("Safari")>-1){
	BROWSER="safari";
}else if(agent.indexOf("Opera")>-1){
	BROWSER="opera";
}

//sayfa yüklendikten sonraki işlemler çağrılıyor
Event.observe(window,"load",function(){
	if(IE6){
		if($("loadingLayer")){
			$("loadingLayer").addClassName("loadingLayer_ie6");
		}else{
			$("loading").addClassName("loading_ie6");
		}
	}else{
		if($("loadingLayer")){
			$("loadingLayer").addClassName("loadingLayer_ie7");
		}else{
			$("loading").addClassName("loading_ie7");
		}
	}
	
	//global html ajax tanımlanıyor
	Ajax.Responders.register({
		method: "post",
		onFailure: function(e){
				showResponses(e);
				$('loading').hide();
			},
		onCreate: function(request){
				/*if($("warning")){
					$("warning").hide();
				}*/
				$('loading').show();
			}, 
		onComplete: function(request){
				setTimeout(function(){$('loading').hide();},1500);
				pageTracker._trackPageview("/ajax"+request.url);
				//alert("/ajax"+request.url);
			}
		}
	);
	
});

/* Sub Menü Fonksiyonları */
function showSubMenu(){
	var child=$(this["child"]);
	child.style.display = 'block';
	clearTimeout(child["timeout"]);
	var parent=$(this["parent"]);
	parent.addClassName("jsmn");  
}

function hideSubMenu(){
  var child=$(this["child"]);
	var parent=$(this["parent"]);
	child["timeout"] = setTimeout(function(){child.style.display = 'none';parent.removeClassName("jsmn");}, 100);
}

function subMenu(parent, child){
  var p = $(parent);
  var c = $(child);
  p["parent"] = p.id;
  c["parent"] = p.id;
  p["child"] = c.id;
  c["child"] = c.id;
	p.onmouseover = showSubMenu;
  p.onmouseout  = hideSubMenu;
  c.onmouseover = showSubMenu;
  c.onmouseout  = hideSubMenu;
}

/* 
 * Genel fonksiyonlar 
 */
 
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

function checkAll(obj){
	var id=obj.form.id;
	$(id).getInputs().each(
		function(val,key){
			if(val.type=="checkbox"){
				val.checked=obj.checked;
			}
		}
	);									
}

function showWarning(msg){
	$('warning').update(msg);
	$('warning').show();
	setTimeout(function(){$("warning").hide()},10000);
}

function showLightWarning(msg){
	$('lightWarning').update(msg);
	$('lightWarning').style.visibility='visible';
	setTimeout(function(){$("lightWarning").style.visibility='hidden'},10000);
}


function parsePrice(str){
	str=str.replace(".","");
	str=str.replace(",",".");
	return parseFloat(str);
}

function round(number,precision){
	var p=Math.pow(10,precision);
	return Math.round(number*p)/p;
}

/* 
 *ürün listeleme ile ilgili fonksiyonlar 
 */
function setPriceFilter(){
	if( $('priceTo').value=="" || $('priceFrom').value=="" ){
		alert('Listelemek istediğin fiyat aralığını gir.');
		$('priceFrom').focus();
	}
	else if( isNaN($('priceFrom').value) || isNaN($('priceTo').value) || parseInt($('priceTo').value) < parseInt($('priceFrom').value) ){
		alert('Geçersiz fiyat aralığı.');
		$('priceFrom').focus();
	}
	else{
		productListFilter.set("priceFrom",$('priceFrom').value);
		setFilter("priceTo",$('priceTo').value);
	}
}

function removePriceFilter(){
	$('priceFrom').value='';
	$('priceTo').value='';
	productListFilter.set("priceFrom",null);
	setFilter("priceTo",null);
}

function setFilter(filter,value){
	productListFilter.set('listPage',null);
	productListFilter.set(filter,value);
	//alert(productListFilter.toQueryString());
	var url="/category/index";
	if(controllerName=="product"){
		url="/product/search";
	}
	new Ajax.Updater("content",
		url,{
			parameters:productListFilter,
			evalScripts:true,
			onSuccess:function(e){new Effect.ScrollTo('body');}
		}
	);
}

/*
 * hızlı arama formunu gönderir
 */
function fastSearchForm(){
	var f=$('fastSearchForm');
	if(f.kategori.value=="" && f.marka.value=="" && f.kelime.value==""){alert('Arama yapabilmek için en az bir kriter girmelisin.');f.kategori.focus();}
	else return true;
	return false;
}

/*
 * sepetten istenilen ürünü çıkarır
 */
function removeFromCart(id){
	new Ajax.Request("/cart/remove",
		{
			parameters: {'id':id},
			onSuccess: function(res){
				res=res.responseText.evalJSON();
				if(res.status=="ok"){
					//showWarning('Ürün sepetten kaldırıldı.');				
					reloadCartList()
				}else{
					showWarning('İşleminiz yapılırken hata oluştu!');
				}
			}
		}
	);
}

/*
 * sağ veya sol kolonda bulunan sepet listesini günceller
 */
function reloadCartList(){
	new Ajax.Request("/cart/column-list",	{
			onSuccess:function(e){
				if(e.responseText.length==0){
					if(!IE6){
						Effect.Fade('ajaxCartLayer',{
								duration: 1, 
								afterFinish:function(e){$('ajaxCartLayer').update("");}
							}
						);
					}else{
						$('ajaxCartLayer').update("");
					}
				}
				else{
					if($('ajaxCartLayer').innerHTML==""){
						if(!IE6){
							$('ajaxCartLayer').hide();
							$('ajaxCartLayer').update(e.responseText);
							Effect.Appear('ajaxCartLayer',{duration: 1 });	
						}else{
							$('ajaxCartLayer').update(e.responseText);
						}
					}else{
						$('ajaxCartLayer').update(e.responseText);
						if(!IE6){
							Effect.Pulsate('ajaxCartLayer',{pulses: 3, duration: 1 });
						}
					}
				}
			}
		}
	);
}

/*
	formlarda giriş yapılan mail adresinin dogrulugunu kontrol eder
*/
function isEmail(x){
	try{
		var desen  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!desen.test(x)){ 
			return true;
		}
	}catch(e){if(debug)alert("isEmail:"+e);}
	return false;
}

/*
 * Telefon numarası geçerlimi kontrol ediyor
 */
function isPhone(code,phone){
	if(code.length<3 || phone.length<7 || isNaN(code) || isNaN(phone)){
		return false;
	}
	return true;
}


/*
 * ismi verilen checkbox seçili değilse seçer, seçili ise seçimi kaldırır
 */
function checkToggle(objName,id){
	var obj=$(objName);
	if(id){
		alert(obj + "-" + obj[id] + "-"+id);
		obj=obj[id];
	}
	if(obj.checked){
		obj.checked=false;
	}else{
		obj.checked=true;
	}
}