var root = location.protocol + '//' + location.host;

$(document).ready(function(){

	// *** Olaylar *** //
	(function($){$.fn.yukseklikEsitle=function(){var nesneSay=this.length;var enYuksek=this.eq(0).height();for(i=1;i<nesneSay;++i){var currHeight=this.eq(i).height();if(currHeight>enYuksek){enYuksek=currHeight}}this.height(enYuksek);return this}})(jQuery);
	
	$('#cart-wrapper').bind('sepeteEkle', function(e, item) {
        $(this).html(item);
	});

    //üye girişi
    $('.UyeLogin').click(function(){memberLogin($(this).attr('alt'),0);return false;});
    $('#uye-login').click(function(){memberLogin('uye-',0);return false;});
    $('#uye-eposta').keydown(function(e){if (e.keyCode == 13) {if ($('#parola').val()=='') $('#parola').focus(); else memberLogin('uye-',0);}});
    $('#uye-parola').keydown(function(e){if (e.keyCode == 13) memberLogin('uye-',0);});
    
    //üye girişi orta kısım
    $('#ug-eposta').focus();
    $('#ug-login').live('click',function(){memberLogin('ug-',0);return false;});
    $('#ug-eposta').keydown(function(e){if (e.keyCode == 13) {if ($('#ug-parola').val()=='') $('#ug-parola').focus(); else memberLogin('ug-',0)}});
    $('#ug-parola').keydown(function(e){if (e.keyCode == 13) memberLogin('ug-',0)});
    $('#uye-kayit-login').click(orderLogin); //üyeliksiz giriş
    
    //bayi girişi
    $('#bayi-login').click(function(e){memberLogin('bayi-', '1');return false;});
    $('#bayi-eposta').keydown(function(e){if (e.keyCode == 13) {if ($('#bayi-parola').val()=='') $('#bayi-parola').focus(); else memberLogin('bayi-', '1');}});
    $('#bayi-parola').keydown(function(e){if (e.keyCode == 13) memberLogin('bayi-', '1');});
	

    $('#ebulten-eposta').keydown(function(e){
        if (e.keyCode == 13)
            saveMaillist();
    });
    
    $('#ebulten-soyad,#ebulten-ad').keydown(function(e){
        if (e.keyCode == 13) {
            if ($(this).attr('id') == 'ebulten-ad' && document.getElementById('ebulten-soyad'))
                $('#ebulten-soyad').focus();
            else
                $('#ebulten-eposta').focus();
        }    
    });

    $('#ebulten-kaydet').click(saveMaillist);
    
    //bloklardaki sepete ekleme butonu
    $('.c-product .GenelButon').click(function(){
        var mainPrId = $(this).attr('alt').split('-');
        
        var prId = parseInt(mainPrId[0]);
        mainPrId = parseInt(mainPrId[1]);
        
        if (mainPrId > 0 && prId > 0) {
    
            sepeteEkle.onSuccess = function() {
                //sepeteEkle.onSuccess = function(){ alert('İşleminiz gerçekleştirilmiştir..') };
                sepeteEkle(prId,'', 1, '', '', mainPrId); 
            };
            
            sepeteEkle(mainPrId, c_altUrunId(), -1);
        }
        else
        if (prId > 0) {
            sepeteEkle.onSuccess = function() {
                $(this).fadeOut().fadeIn();
            };
            sepeteEkle(prId, c_altUrunId(), -1);
        }
        
        return false;
    });

    
    
    $('#site-yorum-gonder').click(function(){
    
        var memberId = $(this).attr('alt');
        var comment  = $('textarea#site-yorum').val();
    
        if (isNaN(memberId) || comment == '') {
            
            return false;
        }
        
        $.ajax({
            type: "POST",
            url : "ajax.php",
            data: "m=Block&fn=siteComment&memberId="+memberId+"&comment="+ comment,
            success : function(msg){
                if (msg > 0)
                    $('#yorum-ekle-tasiyici').html('Yorumunuz onaylandıktan sonra yayınlanacaktır. Teşekkür ederiz..');
            }
        });
        
        return false;
    })
    
    
    ////slider.js
    
    $('.vitrin_tab').click(function (e){
        var tabId    = this.hash;
        var holderId = $(this).parent().attr('id').replace("tab-holder-","");
        var parentId = $(this).attr('alt');
        
        checkURL(tabId, $('#tab-content-' + parentId));
        
        $("#tab-holder-"+holderId+" a").removeClass('Aktif');
        
        $(this).addClass('Aktif');

	});
    
    
	$('.vitrin_tab_ileri').click(function (e){
        lasturl="";

        var parentId = this.hash.replace("#sekme","");
        
        blokId = $("#tab-" + parentId).attr("value");

        checkURL(blokId+'_ileri', $('#tab-content-' + parentId));
	});
    
    
	$('.vitrin_tab_geri').click(function (e){
        lasturl="";
        
        blokId = $("#tab-"+this.hash.replace("#sekme","")).attr("value");
        var parentId = $(this).attr('alt');

        checkURL(blokId+'_geri', $('#tab-content-' + parentId));
	});
    
    $('.Vitrin .Sekmeler a:first').each(function(){ $(this).addClass('Aktif'); })




    var blokId="";
    var blokId_="";
    var lasturl="";

    function checkURL(hash,holder)
    {
        if(!hash) hash=window.location.hash;

        if(hash != lasturl) {
            lasturl=hash;
            // FIX - if we've used the history buttons to return to the homepage,
            // fill the pageContent with the default_content
            if(hash!="")
            loadPage(hash,holder);
        }
    }

    function loadPage(url,holder) {
        url=url.replace('#sekme','');
        
        $(holder).css('visibilty', 'hidden');
        
        var id = holder.attr('id');
        
        if (id != null)
            $("#loading-" + id.replace('tab-content-','')).show();
            
        $('.vitrin_tab_ileri').css('display', 'none !important');
        $('.vitrin_tab_geri').css('display', 'none !important');
        
        $.ajax({
            type: "POST",
            url : "ajax.php?m=Block&fn=tabContent",
            data: 'blok='+url,
            dataType: "html",
            success : function(msg){
                if (id != null)
                    $("#loading-" + id.replace('tab-content-','')).hide();
                
                
                $(holder).css('visibility', 'hidden');
                $(holder).html(msg);

                $(holder).fadeOut(100);
                
                $(holder).css('visibility', 'visible');
                
                $(holder).fadeIn(300, function() {
                    $('.vitrin_tab_ileri').css('display', 'block !important');
                    $('.vitrin_tab_geri').css('display', 'block !important');
                });
            }
        });
    }
    
    //////////
    
    
    
    
    //CLOSING POPUP
	//Click the x event!
	$("#popupContactClose").click(function(){
		disablePopup();
	});
	//Click out event!
	$("#overlay").click(function(){
		disablePopup();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
    
    //// init popup

    var hash =  window.location.hash;

    if (hash.substr(0, 3) == '#T_') {
        
        hash = hash.replace('#T_', '');
        
        hash = hash.split('_|_');
        
        var block = hash[0];

        popup(block, hash[1]);

        window.location.hash = '#';
    }
    /////////
});





function c_altUrunId() {
    var c_altUrunId = '';
    if (document.getElementById('AltUrunId'))
        c_altUrunId = document.getElementById('AltUrunId').value;
    
    return c_altUrunId;
}

    


// *** Fonskiyonlar *** //

var sepeteEkle;
sepeteEkle.onSuccess = undefined;


var sepeteGit = function() {
    location.href = 'Sepet.php';
}

var sepetPopup = function() {
    //...
}

function sepeteEkle(urunId,altUrunId, adet, onceHtml, sonraHtml, iliskiliAnaUrunId){
	
	if ( altUrunId == 'sec' ||  (altUrunId != '' && altUrunId < 0)) {
        if (sepeteEkle.onAlturunAlert != undefined) {
            sepeteEkle.onAlturunAlert();
            
            sepeteEkle.onAlturunAlert = undefined;

            return false;
        }
        else {
            //popup('Urundetay','{"Uid":"' + urunId + '"}');
            alert(l_arr['alt_urun_seciniz_uyari']);
        }
		return false;
	}

	$.ajax({
		type: "POST",
		url: "ajax.php",
		data : {
            m           : 'Cart',
            fn          : 'add2Cart',
            urunId      : urunId,
            altUrunId   : altUrunId,
            adet        : adet,
            iliskiliAnaUrunId : iliskiliAnaUrunId
        },
		success: function(cevap) {

            var r = $.parseJSON(cevap);

            if (r.success == "true") {
            
                if (r.url != '') {
                    location.href = r.url;
                }
                else
                if (sepeteEkle.onSuccess != undefined) {

                    sepeteEkle.onSuccess();

                    sepeteEkle.onSuccess = undefined;
                }
            
                $('#cart-wrapper').trigger('sepeteEkle', stripslashes(r.html));

                var clas = $("#Sepet"+urunId).attr("class");

                if (onceHtml==undefined )
                    onceHtml = '<a href="#" class="'+clas+'"><span>'+l_arr['sepete_ekle']+'</span></a>';
                else
                    onceHtml = $("#Sepet"+urunId).html();
                    
                if ( sonraHtml==undefined )
                    sonraHtml = '<a href="#" class="'+clas+'"><span>'+l_arr['sepete_eklendi']+'</span></a>';
                else
                    sonraHtml = $("#Sepet"+urunId).html();

                $("#Sepet"+urunId).hide().html(sonraHtml).fadeIn(1000,function(){
                    
                    if (onceHtml != sonraHtml)
                    setTimeout(function(){
                            $("#Sepet"+urunId).html(onceHtml);
                    },1000);
                });

                if (document.getElementById('cart-soft-message')) {
                    $('#cart-soft-message').fadeIn('slow').delay(1000).fadeOut('fast');
                }
                if (document.getElementById('cart-soft-count')) {
                    
                    $('#cart-soft-count').animate({
                        opacity: 0.25
                      }, 500, function() {
                          $(this).find('span').html(r.count);
                        $(this).animate({
                            opacity: 1
                        })
                      });
                }
            }
            else {
                alert(r.msg);
            }
		}
	});
	return false;
}

function alarmListemeEkle(urunId, fiyat, kur) {

    popup('AlarmListem', '{"Uid":"'+urunId+'","Fiyat":"'+fiyat+'","Kur":"'+kur+'"}');
    
    return true;
}


function alisverisListemeEkle(urunJson) {

    if (urunJson > 0)
        urunJson = '"' + urunJson + '"';

    popup('AlisverisListem', '{"Uids":['+urunJson+']}');
    
    return true;
}

function sepetiAlisverisListemeEkle() {

    var id, json = '';
    
    $("#SepetForm .satir-sil").each(
        function(){
            id = $(this).attr("alt");
            id = id.split("-");
            json += '"' + id[0] + '",';
        }
    );
    
    if (json != '') {
        json = json.substring(0, json.length -1);
        alisverisListemeEkle(json);
    }
    
	return false
}

function stoktaOluncaBildir(urunId, altUrunId) {

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data : "m=Block&fn=add2NotifyList&prId="+urunId+"&subPrId="+altUrunId,
        success: function(cevap) {
            alert(cevap);
        }
    })
}

function urunGoster(ref, tasiyan) {

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data : "m=Block&fn=productView&ref="+ ref,
        success: function(cevap) {
            $("#"+tasiyan).html(cevap);
        }
    });
}


var popup;
popup.onSuccess = undefined;

function popup(block, paramsJson) {

    $.ajax({
        type : "POST",
        url  : "ajax.php",
        dataType: "json",
        data : {
            m      : 'Block',
            fn     : 'initPopup',
            block  : block,
            params : paramsJson
        },
        complete: function(jsonObj) {

            var jsonObj = $.parseJSON(jsonObj.responseText);

            if (jsonObj.success == "false") {

                if (jsonObj.url != null) {
                    popup(jsonObj.url, '{"Referer":"'+ location.href +'","Hash":"'+block+'_|_'+addslashes(paramsJson)+'"}');
                    return;
                }
                else
                if (jsonObj.msg != '') {
                    loadPopup('Uyarı..', jsonObj.msg);
                    return false;
                }
            }
            else
            if (jsonObj.success == "true") {
            
                loadPopup(jsonObj.data.header, jsonObj.data.content);

                $('#popup-content .UyeForm h3').remove();

                if (popup.onSuccess != null) {
                    popup.onSuccess();
                    popup.onSuccess = null;
                }
            }
            else {
                alert('Beklenmeyen durum oluştu.');
            }
        }
    })
}




var formMap = new Array();
// overrride from div ids to alert user 

function memberLogin(idPrefix, isVendor) {
    
    formMap['username'] = idPrefix + 'eposta';
    formMap['password'] = idPrefix + 'parola';
    formMap['message'] = idPrefix + 'mesaj';
    formMap['loading'] = idPrefix + 'loading';
    formMap['login'] = idPrefix + 'login';

    var username = $('#'+formMap['username']).val();
    var password = $('#'+formMap['password']).val();
    
    if (username == '' || password == '') {
        $('#'+formMap['message']).html(l_arr['eposta_sifre_bos']);
        $('#'+formMap['password'])
        return false;
    }
    
    $('#'+formMap['login']).css('display','none !important');
    $('#'+formMap['loading']).show();
    

    $.ajax({
        type : "POST",
        url  : "ajax.php",
        data : "m=Member&fn=memberLogin&user="+username+'&pass='+password+'&vendor='+parseInt(isVendor),
        success: function(json) {
            var data = $.parseJSON(json);
            
            var elId = '';
            
            if (data.isLogin == 0) {
                $('#'+formMap['message']).html(stripslashes(data.msg));
                $('#'+formMap['username']).focus();
                
                $('#'+formMap['login']).css('display','block !important');
                $('#'+formMap['loading']).hide();
            }
            else
            if (data.isLogin == 1) {
                if (data.hash != '') {
                    location.hash = data.hash;
                    location.reload(true);
                }
                else
                if (data.redirectionUrl != '')
                    location.href = data.redirectionUrl;
                else
                if (strpos(location.href, 'Cikis', 0) !== false)
                    location.href = location.href.replace('?B=Cikis', '');
                else
                    location.reload();
            }
        }
    });
    return false;
}


    function sl(el){
    
        var ld = '<img id="loading-temp" src="'+root+'/e3/theme/standart/images/zoomloader.gif />';
        
        console.log(ld);

        $(el).html(ld);
    }

function orderLogin(e) {

    //sl(e.target);
    
    //if (document.getElementById('default-value-control')) {
        $('form#HizliUyelik input[type=text]').each(function(){
        
            if ($(this).val() != '' && $(this).attr('defaultValue') == $(this).val())
                $(this).val('');
        }); 
    //}
    
    
    
    var data;
    if ($('form#HizliUyelik').length > 0)
        data = $('form#HizliUyelik').serialize();
    else
        data = "name="+$('#uye-ad').val()+"&surname="+$('#uye-soyad').val()+"&mail="+$('#uye-eposta').val()+"&tel="+$('#uye-tel').val();

    $.ajax({
        type : "POST",
        url  : "ajax.php?m=Member&fn=orderLogin",
        data : data,
        success: function(json) {
            var data = $.parseJSON(json);
            var elId = '';

            if (data.requiredFields.length > 0) {
                for (var i in data.requiredFields) {

                    var elId = 'uye-' + data.requiredFields[i];

                    if (document.getElementById(elId)) {
                        $('#' + elId).focus();
                        break;
                    }
                }
            }
            
            if (data.isLogin == 0) {
                $('#uye-login-msg').html(data.msg);
            }
            else
            if (data.isLogin == 1) {
                if (data.activation == "true") {
                    $('#activation-msg').html(stripslashes(data.msg));
                }
                else    
                if (data.redirectionUrl != '')
                    location.href = data.redirectionUrl;
                else
                    location.reload();
            }
        }
    });
    return false;
}


function saveMaillist() {

    var ad = $('#ebulten-ad').val();
    var soyad = $('#ebulten-soyad').val();
    var eposta = $('#ebulten-eposta').val();
    $.ajax({
        type: "POST",
        url: "ajax.php",
        data : "m=Member&fn=add2MailList&ad="+ad+"&soyad="+soyad+"&eposta="+eposta,
        success: function(r) {

            var msgText = document.getElementById('ebulten-msg');
            var msg = '';

            switch (r) {

                case '1' : 
                    msg = 'Lütfen adınızı giriniz.';
                    break;
                case '2' : 
                    msg = 'Lütfen e-posta giriniz.';
                    break;
                case '3' : 
                    msg = 'Lütfen adınızı ve e-posta giriniz.';
                    break;
                case '0' : 
                    msg = 'Lütfen e-posta adresinizi kontrol ediniz.';
                    break;
                    
                default  :
                    if (ad == 'e-bulten')
                        msg = 'E-bültenimize kayıt olduğunuz için teşekkür ederiz.';
            }

            if (msg == '')
                $('.EBulten').html(r);
            else
            if (msgText)
                msgText.innerHTML = msg;
            else
                alert(msg);
        }
    });
    return false;
}



function siteTavsiyeEt(prId) {

    $.ajax({
        type: "POST",
        url: "ajax.php",
        data : {
            "m"  : "Block",
            "fn" : "siteAdvice",
            "GonderenAdi"   : $("#site-tasiye-isim").val(),
            "GonderenEposta": $("#site-tavsiye-eposta").val(),
            "AliciAdi"      : $("#site-alici-adi").val(),
            "AliciEposta"   : $("#site-alici-eposta").val(),
            "Mesaj"         : $("#site-tavsiye-mesaj").val()
        },
        success: function(r) {

            var jsonObj = $.parseJSON(r);
            
            if (jsonObj.success == 'false') {
            
                if (jsonObj.errCode == 1) {
                    
                    popup('UyeGiris');
                    return false;    
                }
                

                alert(jsonObj.msg);
            }
            else {
                alert('Sitemizi tavsiye ettiğiniz için teşekkür ederiz.. İyi alış verişler');    
            }
        }
    });
    
    return false;
}



function kategoriYukle(katId, comboId, ilkSecenek) {

    if (katId === '') {
        
        var List = document.getElementById(comboId);
                
        for (var x=List.length; x>=0; x--)
            List[x] = null;
            
        List[0] = new Option('', ''); 
            
        return false;
    }

    $.getJSON('Json/Kategoriler.php?KatId=' + katId,
        function(JSON) {
            
            var List = document.getElementById(comboId);
                
            for (var x=List.length; x>=0; x--)
                List[x] = null;
                
            var option = new Option('Yükleniyor..!','');
            try { 
                List.add(option, null); 
            }
            catch (ex) {
                List.add(option);
            }
            
            $.each(JSON.data, 
                function(i, kategori) {
                
                    option = new Option(kategori.Ad, kategori.id);
                    try { 
                        List.add(option, null); 
                    }
                    catch(ex) { 
                        List.add(option); 
                    }
            });
            
            if (ilkSecenek != undefined && ilkSecenek != null) {
            
                option = new Option(ilkSecenek, '');
                
                List[0] = option;
                
                List[0].selected = "1";
            }
            else
                List[0] = null;
        }
    );

}



function ilceComboYukle(ilComboId, ilceComboId) {
    $('#' + ilComboId).change(function() { ilceDoldur(ilceComboId, $(this).val()) });
}

function ilceDoldur(ilceComboId, ilKod, ilceSec) {
    $.ajax({
        type    : 'GET',
        url     : 'ajax.php',
        data    :  {
            m   : 'Member',
            fn  : 'provinceLocationsJson',
            kod : ilKod
        },
        success: function(JSON) {

            var List = document.getElementById(ilceComboId);

            for (var x=List.length; x>=0; x--)
                List[x] = null;

            var option = new Option('Yükleniyor..!','');
            try {
                List.add(option, null);
            }
            catch (ex) {
                List.add(option);
            }

            var data = $.parseJSON(JSON);

            for (var i=0; i<data.length; i++) {

                var option = new Option(data[i], data[i]);
                try {
                    List.add(option, null);
                }
                catch(ex) {
                    List.add(option);
                }
            }
            List[0] = null;

            if (ilceSec != null)
                $('#' + ilceComboId).val(ilceSec);
        }
    });
}


// tools

function getCheckedArray(formId,el) {
	 if(document.forms[formId]) {
		var chkArr = new Array();
		var objCheckBoxes = document.forms[formId].elements[el];
		if(objCheckBoxes){
			var countCheckBoxes = objCheckBoxes.length;
			for(var i=0; i<countCheckBoxes; i++){
				if (objCheckBoxes[i].checked){
					chkArr.push(objCheckBoxes[i].getAttribute('id'));
				}
			}
		}
		return chkArr;
	}
	return false;
 }
 
 function pop(name,opt) {
 
	if (opt==undefined)
		opt = {};
 
	if (opt.fullscreen) {
		opt.width = screen.width-20;
		opt.height = screen.height-80;
		opt.top = 0;
		opt.left = 0;
		opt.resizable = 0;
		opt.scrollbars = 0;
	}
	else {
		if (opt.width==undefined)
			opt.width = 800;

		if (opt.height==undefined)
			opt.height = 600;

		if (opt.top==undefined)
			opt.top    = (screen.height - opt.height)/2;

		if (opt.left==undefined)
			opt.left   = (screen.width  - opt.width)/2;

		if (opt.scrollbars == undefined)
			opt.scrollbars = 0;

		opt.resizable = 1;
	}
	
	if (opt.toolbar == undefined)
			opt.toolbar = 0;
	if (opt.toolbar == undefined)
			opt.menubar = 0;

	opt.location = 0;
	opt.status = 0;
	opt.directories = 0;
	
	var params = '';
	for (var param in opt)
		params += param + '=' + opt[param]+',';
	
	params = params.substr(0,params.length-1);
	
    newwindow=window.open('popup.php?P='+name, name, params);
	if (window.focus) {newwindow.focus()}
	return false;
 }
 
 function initPaging(parentId) {

	var pages   = $('#' + parentId + " #pagingMenu li");
	var loading = $(" div:#loading");
	var content = $('#' + parentId + " div:#content");

        //show loading bar
	var sl = function showLoading(){
		loading
			.css({visibility:"visible"})
			.css({opacity:"1"})
			.css({display:"block"})
		;
	}
	//hide loading bar
	var hl = function hideLoading(){
		loading.fadeTo(1000, 0);
	}

        //Manage click events
	pages.click(function(){

		//show the loading bar
		sl();

		//Highlight current page number
		pages.css({'background-color' : ''});
		$(this).css({'background-color' : 'yellow'});

		//Load content
		var pageNum = this.id;
                if(isNaN(pageNum))
                    pageNum = $(this).attr('rel');
                else {
                    var prev = $('#' + parentId + " #pagingMenu li#prev");
                    var next = $('#' + parentId + " #pagingMenu li#next");
                    prev.attr('rel', parseInt(pageNum)-1);
                    next.attr('rel', parseInt(pageNum)+1);
                }
		var targetUrl = "ajax.php?m=Block&fn=pagingData&table=1&page=" + pageNum + "&" + $("#pagingForm").serialize() + " #content";
		content.load(targetUrl, hl);
	});

	//default - 1st page
	$('#' + parentId + " #1").css({'background-color' : 'yellow'});
	var targetUrl = "ajax.php?m=Block&fn=pagingData&table=1&page=1&" + $("#pagingForm").serialize() + " #content";
	sl();
	content.load(targetUrl, hl);
}

function log(msg) {
    if ($.browser.msie)
        ieLog(msg);
    else
        console.log(msg);
}
function ieLog(msg, empty) {
    if (!document.getElementById('ie-log'))
        $(document.body).append('<div id="ie-log"></div>');
    if (empty)
        $('#ie-log').html(msg);
    else
        $('#ie-log').html(msg + '<br />'+$('#ie-log').html());

    $('#ie-log').css({position: 'fixed', bottom:'0', padding:'3px', background: 'none #3FA', width:'100%', font:'10px sans-serif'});
}

function RefreshImage(ImageId, NewImageSrc){
   var img = document.getElementById(ImageId);
   img.src = NewImageSrc+'?'+Math.random();
}

function stripslashes (str) {
    return (str + '').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
        case '\\':
            return '\\';
        case '0':
            return '\u0000';
        case '':
            return '';
        default:
            return n1;
        }
    });
}

function addslashes (str) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes
    //
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/addslashes
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

function strpos (haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

function isset(){var a=arguments;var l=a.length;var i=0;if(l==0){throw new Error('E');}while(i!=l){if(typeof(a[i])=='undefined'||a[i]===null){return false}else{i++}}return true}


function round(number, digits) {
    var multiple = Math.pow(10, digits);
    var rndedNum = Math.round(number * multiple) / multiple;
    return rndedNum;
}


function getQueryVariable(variable) { 

    var query = window.location.search.substring(1).toLowerCase();

    var vars = query.split("&");

    for (var i=0; i < vars.length; i++) {

        var pair = vars[i].split("=");

        if (pair[0] == variable.toLowerCase()) {
            return pair[1];
        }
    }
}


//blok_resim.js
function YeniResimGoster(Nesne){document.getElementById(Nesne).style.display='block';}
function YeniResimGizle(Nesne){document.getElementById(Nesne).style.display='none';}
function BRGoster(Nesne){document.getElementById(Nesne).style.visibility='visible';}
function BRGizle(Nesne){document.getElementById(Nesne).style.visibility='hidden';}

function BlokResim(Nesne){
	if (document.getElementsById(Nesne).style.display='none') document.getElementsById(Nesne).style.display='block';
	else  document.getElementsById(Nesne).style.display='none'
	}


function SetAllCheckBoxes(FormName, FieldName, CheckValue){
    if(!document.forms[FormName])
            return;
    var objCheckBoxes = document.forms[FormName].elements[FieldName];
    if(!objCheckBoxes)
            return;
    var countCheckBoxes = objCheckBoxes.length;
    if(!countCheckBoxes)
            objCheckBoxes.checked = CheckValue;
    else
        // set the check value for all check boxes
        for(var i = 0; i<countCheckBoxes; i++)
                objCheckBoxes[i].checked = CheckValue;
}
var sepetCokluUrun = [];
function SepetCokluGuncelle(uid,durum,adet){
    var UrunId='';
    var Adet='';
    var i;
    
    sepetCokluUrun[uid] = durum?adet:0;
    
    for (i in sepetCokluUrun){
        UrunId += i + ',';
        Adet += sepetCokluUrun[i] +',';
    }

    Adet = Adet.substring(0,Adet.length-1);
    UrunId = UrunId.substring(0,UrunId.length-1);

    document.getElementById("sepet-coklu-islem").setAttribute("href","Sepet.php?UrunId="+UrunId+'&'+'Adet='+Adet);
}
////////




function newsscoller(prev,id) {

	//Get the current selected item (with selected class), if none was found, get the first item
	var current_image = $('#gallery'+id+' a.selected').length ? $('#gallery'+id+' a.selected') : $('#gallery'+id+' a:first');
	var current_excerpt = $('#excerpt'+id+' li.selected').length ? $('#excerpt'+id+' li.selected') : $('#excerpt'+id+' li:first');

	//if prev is set to 1 (previous item)
	if (prev) {
		
		//Get previous sibling
		var next_image = (current_image.prev().length) ? current_image.prev() : $('#gallery'+id+' a:last');
		var next_excerpt = (current_excerpt.prev().length) ? current_excerpt.prev() : $('#excerpt'+id+' li:last');
	
	//if prev is set to 0 (next item)
	} else {
		
		//Get next sibling
		var next_image = (current_image.next().length) ? current_image.next() : $('#gallery'+id+' a:first');
		var next_excerpt = (current_excerpt.next().length) ? current_excerpt.next() : $('#excerpt'+id+' li:first');
	}

	//clear the selected class
	$('#excerpt'+id+' li, #gallery'+id+' a').removeClass('selected');
	
	//reassign the selected class to current items
	next_image.addClass('selected');
	next_excerpt.addClass('selected');

	//Scroll the items
//	$('#mask-gallery'+id).scrollTo(next_image, 800);
//	$('#mask-excerpt'+id).scrollTo(next_excerpt, 800);
}
/////////////

/***************************/
//@Author: Adrian "yEnS" Mato Gondelle
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@license: Feel free to use it, but keep this credits please!
/***************************/

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;


function overlay(show) {
    //only need force for IE6
    $("#overlay").css({"opacity": "0.8","height": document.documentElement.clientWidth});

    if (show)
        $("#overlay").fadeIn("slow");
    else
        $("#overlay").fadeOut("slow");
}

//loading popup with jQuery magic!
function loadPopup(header, content) {
	//loads popup only if it is disabled
	if(popupStatus==0){
		overlay(true);
        
        $("#popup-header").html(header);
        $("#popup-content").html(content);
            
        centerPopup();
        
		$("#popupContact").fadeIn("slow");
		popupStatus = 1;
	}
}

//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		overlay(false);
		$("#popupContact").fadeOut("slow");
		popupStatus = 0;
	}
}

//centering popup
function centerPopup(){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;

	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();
	//centering
	$("#popupContact").css({
		"position": "fixed",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
}


////T-soft.js
function getVar(v){
    var q = window.location.search.substring(1);
    var vs;

    if (q=="" && (v=="Kid" || v=="Uid" || v=="MarkaId" || v=="ModelId")) {
        
        q = window.location.toString();
        vs = q.split("/");
        q = vs[vs.length-1];
        vs = q.split(",");

        var regs = new Array();
        regs["Kid"] = /\K\d+$/;
        regs["Uid"] = /\U\d+$/;
        regs["MarkaId"] = /\M\d+$/;
        regs["ModelId"] = /\Y\d+$/;

        for (var i=0;i<vs.length;i++){
            if (regs[v].test(vs[i])) {
                return vs[i].substr(1);
            }
        }
    }
    else {
        vs = q.split("&");
        for (var i=0;i<vs.length;i++){
            var p = vs[i].split("=");
            if (p[0] == v) {
                return p[1];
            }
        }
    }
    return '';
}
//function getVar(v){var q = window.location.search.substring(1);var vs = q.split("&");for (var i=0;i<vs.length;i++){var p = vs[i].split("=");if (p[0] == v) {return p[1];}}return '';}
function Kucult(id,oran){setTimeout("document.getElementById('"+id+"').width=document.getElementById('"+id+"').width/"+oran+";",1000);}
function isset(){var a=arguments;var l=a.length;var i=0;if(l==0){throw new Error('E');}while(i!=l){if(typeof(a[i])=='undefined'||a[i]===null){return false}else{i++}}return true}
/////

function SelectText(element) {
    var text = document.getElementById(element);
    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    
    return re.test(email);
}

var baseUrl = getHostUrl();

function getHostUrl() {
    var scripts = document.getElementsByTagName('script'), path, i, scriptSrc, match;

    for (i = 0, ln = scripts.length; i < ln; i++) {
        scriptSrc = scripts[i].src;

        match = scriptSrc.match(/general\.js$/);

        if (match) {
            path = scriptSrc.substring(0, scriptSrc.length - 13);
            break;
        }
    }
    return path;
}

Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };
 
 
 
//fırsat ürün sayaç fonksiyonları
//######################################################################################
// Author: ricocheting.com
// Version: v2.0
// Date: 2011-03-31
// Description: displays the amount of time until the "dateFuture" entered below.

// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture1 = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture1 = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm
function GetCount(ddate,iid){

	dateNow = new Date();	//grab current date
	amount = ddate.getTime() - dateNow.getTime();	//calc milliseconds between dates
	delete dateNow;

	// if time is already past
	if(amount < 0){
		document.getElementById(iid).innerHTML = "<b>Fırsattan yararlanma süresi dolmuştur..</b>";
		if (document.getElementById('tsoft_counter_label'))
		  document.getElementById('tsoft_counter_label').innerHTML = "";
	}
	// else date is still good
	else{
		days=0;hours=0;mins=0;secs=0;out='<span>Bu fırsat için kalan süreniz:</span><ul class="counter_digits">';

		amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

		days = intToClockDigit(Math.floor(amount/86400));//days
		amount=amount%86400;

		hours = intToClockDigit(Math.floor(amount/3600));//hours
		amount=amount%3600;

		mins = intToClockDigit(Math.floor(amount/60));//minutes
		amount=amount%60;

		secs = intToClockDigit(Math.floor(amount));//seconds

		if(days > 0)
		out += '<li class="gun">' + days + "</li>";
		out += '<li class="saat">' + hours + "</li>";
		out += '<li class="dakika">' + mins + "</li>";
		out += '<li class="saniye">' + secs + "</li>";
        out += '</ul>';
        
		document.getElementById(iid).innerHTML=out;

		var x = setTimeout(function(){ GetCount(ddate,iid) }, 1000);
	}
}

function intToClockDigit(val) {
    
    return (val.toString().length === 1) ? ('0' + val) : val;
}

//<input type="text" size="10" maxlength="10" onkeyup="dtval(this,event)">
function dtval(d, e) {
    var pK = e ? e.which : window.event.keyCode;
    if (pK == 8) {
        d.value = substr(0, d.value.length - 1);
        return;
    }
    var dt = d.value;
    var da = dt.split('/');
    for (var a = 0; a < da.length; a++) {
        if (da[a] != +da[a]) da[a] = da[a].substr(0, da[a].length - 1);
    }
    if (da[0] > 31) {
        da[1] = da[0].substr(da[0].length - 1, 1);
        da[0] = '0' + da[0].substr(0, da[0].length - 1);
    }
    if (da[1] > 12) {
        da[2] = da[1].substr(da[1].length - 1, 1);
        da[1] = '0' + da[1].substr(0, da[1].length - 1);
    }
    if (da[2] > 9999) da[1] = da[2].substr(0, da[2].length - 1);
    dt = da.join('/');
    if (dt.length == 2 || dt.length == 5) dt += '/';
    d.value = dt;
}

