// GLOBALS
var AppConfig = {
    sid : $.cookie('PHPSESSID'),
    username : $.cookie('username')
}
var nl = "\n"
var userOnline = false


$(document).ready(function() {
    //    Check if user is online
    var d=new Date()
    var epoch=(d.getTime()-d.getMilliseconds())/1000
    var ttl=180*60
    var online=false
    if ($.cookie('justlogged')&&(1==$.cookie('justlogged'))&&$.cookie('username')&&$.cookie('PHPSESSID')) {
        $.cookie('lastupdate', epoch, {
            path:'/'
        })
        $.cookie('justlogged', '', {
            expires:-1,
            path:'/'
        })
        online=true
    } else if ($.cookie('lastupdate')&&((epoch-$.cookie('lastupdate'))<ttl)&&$.cookie('username')&&$.cookie('PHPSESSID')) {
        online=true
    }
    if (online) {
        var timer=setInterval("keepAlive("+ttl+")", ttl/6*1000)
    }
    //    Show datas for logged in/logged out users
    var classToShow=online?'.logged_in':'.visitor'
    if (online) userOnline = true
    $(classToShow).show()
    if (online) {
        if ('STANDART' !== $.cookie('PACKAGE')) {
            //$('body').addClass('gold-user')
        }
        if ($('a.myusername').length != 0) {
            $('a.myusername').text($.cookie('username'))
        }
    }

    //    Loading APE
    if (AppConfig.username && 0 < AppConfig.username.length) {
        var host = document.location.host
        if (host.indexOf('www.') === 0 || host.indexOf('wws.') === 0 || host.indexOf('wwn.') === 0) {
            host = host.substr(4)
        }
        var realplexor = new Dklab_Realplexor(
            "http://ape."+host+"/",  // Realplexor's engine URL
            "sites_yehju" // namespace (optional)
            )
		
        realplexor.subscribe(AppConfig.sid, function() {})
        realplexor.subscribe("mailnotif", function(data) {
            openMessagePopupDiv(data)
            })
        realplexor.execute()
    }

    //    Setting thumbs
    if ($('strong.showThumb').length!=0 && typeof $('strong.showThumb').imgPreview=='function') {
        $('strong.showThumb').imgPreview({
            srcAttr:'rel'
        })
    }
    if ($('.profile_photo_link').length!=0 && typeof $('.profile_photo_link').lightBox=='function') {
        if ($.cookie('username')) {
            $('.profile_photo_link').lightBox()
        } else {
            $('.profile_photo_link').each(function(i, elem) {
                elem.onclick=function() {
                    alert('Fotoğrafların büyük halini görmek için üye olmanız gerekmektedir !')
                    return false
                }
                elem.href='/visitor/loginpage/'
            })
        }
    }

    //    AJAX bulk checking online status of users on the page
    var id
    var ids=[]

    $('em.man').add('em.woman').add('a.man').add('a.woman').add('div.man').add('div.woman').each(function(i, elem) {
        if (elem.id&&!$(elem).hasClass('online')&&''!=(id=elem.id.replace('user', '').replace(/_/g, '')))ids.push(id)
    })

    ids=jQuery.unique(ids)
    if (0!=ids.length) {
        var joinedids=ids.join(',')
        $.get("/users/checkOnlineStatus/?ids="+joinedids, function(data) {
            if ('false'!=data) {
                userids=eval(data)
                $(userids).each(function(i, elem) {
                    $('.user_'+elem).addClass('online')
                })
            }
        })
    }

    //    Validate forms with 'validate' class
    if ($('form.validate').length!=0) {
        $('form.validate').validate()
    }

    // Submit forms by ENTER key <IE fix>
    if ($.browser.msie) {
        $(function() {
            $('input, select').keydown(function(e) {
                if (e.keyCode == 13) {
                    $(this).parents('form').submit()
                    return false
                }
            })
        })
    }

    //    Platinum bulk form
    if ($('#platinBulkForm').length!=0) {
        $("#useBulks").click(function () {
            $('#bulkForm').slideDown()
        })
        onCountryChange('#country', '#city')
        $(function(){
            $('#msg').keyup(function() {
                limitChars('msg', 500, 'charlimitinfo')
            })
        })
        var bForm = new bulkForm('platinBulkForm')
    }

    //    Login fields mask
    if ($('#loginLogin').length!=0) {
        masker('#loginLogin','rumuz')
        masker('#loginPassword', '****')
    }

    $(function() {
        if ($(".datepicker").length!=0) {
            $(".datepicker").datepicker($.datepicker.regional['tr'])
            $( ".datepicker" ).datepicker( "option", "altField", '#datepickerfield' )
        }
    })

    if(userOnline && location.pathname.match(/^.*visitor\/home.*$/)) {
        $.getJSON('/visitor/inboxCount/', function(total) {
            if (false !== total) {
                $.cookie('msgTotal', total, {
                    path:'/'
                })
                mpStatusTextUpdate(total)
            }
        })
    }
    if(userOnline && !location.pathname.match(/^.*messages\/inbox.*$/)) {
        var total = $.cookie('msgTotal')
        mpStatusTextUpdate(total)
    }
})

function mpStatusTextUpdate(msgs) {
    if (1 > msgs) {
        $('#mpStatusBar').slideUp()
    } else {
        $('#mpStatusBar').slideUp('slow', function(){
            $('#mpStatusText').html('Toplam ' + msgs + ' yeni mesajınız var')
            $('#mpTotal').html(msgs)
        })
        $('#mpStatusBar').slideDown()
    }
}

function upcheck() {
    var ok = true
    if (''==$("#loginLogin").val() || ''==$("#loginPassword").val()) {
        ok = false
    }
    if (ok && ('rumuz'==$("#loginLogin").val() || '****'==$("#loginPassword").val())) {
        ok = false
    }
    if (ok) {
        return true
    }
    alert("Lütfen kullanici adi ve şifrenizi yaziniz")
    return false
}

function openMessagePopupDiv(data) {
    //    Inspired by LightBox
    if ('message' == data.type) {
        mpStatusTextUpdate(data.total)
        $.cookie('msgTotal', data.total, {
            path:'/'
        })
    }
    var overlayBgColor='#000'
    var overlayOpacity=0.8
    $('body').append('<div id="jquery-overlay"></div>')
    var arrPageSizes=getPageSize()
    var arrPageScroll=getPageScroll()
    $('#jquery-overlay').css({
        backgroundColor:overlayBgColor,
        opacity:overlayOpacity,
        width:arrPageSizes[0],
        height:arrPageSizes[1]
    }).fadeIn()
    $("#MessagePopup").show()
    $('#jquery-overlay').css({
        width:arrPageSizes[0],
        height:arrPageSizes[1]
    })
    $('#mpNick').html(data.from)
    $('#mpAge').html(data.senderAge)
    $('#mpCity').html(data.senderCity)
    $('#mpThumb').attr('src', data.thumb)
    $('#mpText').html(data.text)
    $('#MessagePopup').addClass(data.type)
    $('#MessagePopup .inner .button-box').text(data.buttonText)
}

function closeMessagePopupDiv() {
    $('#jquery-overlay').remove()
    $('#MessagePopup').hide()
}

function openLoginDiv() {
    //    Inspired by LightBox
    var overlayBgColor='#000'
    var overlayOpacity=0.8
    $('body').append('<div id="jquery-overlay"></div>')
    var arrPageSizes=getPageSize()
    var arrPageScroll=getPageScroll()
    $('#jquery-overlay').css({
        backgroundColor:overlayBgColor,
        opacity:overlayOpacity,
        width:arrPageSizes[0],
        height:arrPageSizes[1]
    }).fadeIn()
    $('#loginDiv').css({
        top:arrPageScroll[1]+(arrPageSizes[3]/10),
        left:arrPageScroll[0]
    }).show()
    $("#loginDiv").show()
    $('#jquery-overlay').css({
        width:arrPageSizes[0],
        height:arrPageSizes[1]
    })
    var arrPageScroll=getPageScroll()
    $('#loginDiv').css({
        top:arrPageScroll[1]+(arrPageSizes[3]/10),
        left:arrPageScroll[0]
    })
}

function closeLoginDiv() {
    $('#jquery-overlay').remove()
    $('#loginDiv').hide()
}

function getPageSize() {
    var xScroll, yScroll

    if (window.innerHeight&&window.scrollMaxY) {
        xScroll=window.innerWidth+window.scrollMaxX
        yScroll=window.innerHeight+window.scrollMaxY
    } else if (document.body.scrollHeight>document.body.offsetHeight) {
        xScroll=document.body.scrollWidth
        yScroll=document.body.scrollHeight
    } else {
        xScroll=document.body.offsetWidth
        yScroll=document.body.offsetHeight
    }
    
    var windowWidth, windowHeight

    if (self.innerHeight) {
        if (document.documentElement.clientWidth) {
            windowWidth=document.documentElement.clientWidth
        } else {
            windowWidth=self.innerWidth
        }
        windowHeight=self.innerHeight
    } else if (document.documentElement&&document.documentElement.clientHeight) {
        windowWidth=document.documentElement.clientWidth
        windowHeight=document.documentElement.clientHeight
    } else if (document.body) {
        windowWidth=document.body.clientWidth
        windowHeight=document.body.clientHeight
    }

    if (yScroll<windowHeight) {
        pageHeight=windowHeight
    } else {
        pageHeight=yScroll
    }

    if (xScroll<windowWidth) {
        pageWidth=xScroll
    } else {
        pageWidth=windowWidth
    }
    
    arrayPageSize=new Array(pageWidth, pageHeight, windowWidth, windowHeight)
    return arrayPageSize
}

function getPageScroll() {
    var xScroll, yScroll
    if (self.pageYOffset) {
        yScroll=self.pageYOffset
        xScroll=self.pageXOffset
    } else if (document.documentElement&&document.documentElement.scrollTop) {
        yScroll=document.documentElement.scrollTop
        xScroll=document.documentElement.scrollLeft
    } else if (document.body) {
        yScroll=document.body.scrollTop
        xScroll=document.body.scrollLeft
    }
    arrayPageScroll=new Array(xScroll, yScroll)
    return arrayPageScroll
}

function popitup(url) {
    newwindow=window.open(url, 'name', 'height=200, width=300')
    if (window.focus) {
        newwindow.focus()
    }
    return false
}

function pleaseregister() {
    alert('Önce üye olmanız gerekiyor')
    document.location='/visitor/join1/'
}

function onBirthDateChange() {
    $('#birthday_selected').val('')
    if ('' != $('#reg_birthdateYear').val() &&
        '' != $('#reg_birthdateMonth').val() &&
        '' != $('#reg_birthdateDay').val() )
        {
        $('#birthday_selected').val('1')
    }
    $('#birthday_selected').valid()
}

function onEmailChange() {
    if (('' != $("#emailnameinput").val()) && ('' != $("#emailserverinput").val())) {
        $('#reg_email').val($('#emailnameinput').val()+'@'+$('#emailserverinput').val())
        $('#reg_email').valid()
    }
}

function onCountryChange(countryId, cityId) {
    if (typeof countryId=='undefined')countryId="#country"
    if (typeof cityId=='undefined')cityId="#city"
    $(countryId).val()!=1?$(cityId).attr('disabled', 'disabled'):$(cityId).attr('disabled', '')
}

var registration = {
    _form : null,
    _homepage : false,
    _disabled : false,

    checkLoginExistence : function(login, elementId) {
        $.get("/users/checkLoginExistence/?login="+login,
            function(data) {
                $("#"+elementId).html(eval(data) ? "Yes" : "No")
            })
    },

    submit : function() {
        this._form.submit()
    },

    onCountryChange : function () {

        ($('#reg_country').val() != 1)
        ? $('#reg_city').attr('disabled', 'disabled')
        : $('#reg_city').attr('disabled', '')
    },

    onBirthDateChange : function () {
        $('#birthday_selected').val('')

        if ('' != $('#reg_birthdateYear').val()
            && '' != $('#reg_birthdateMonth').val()
            && '' != $('#reg_birthdateDay').val()) {
            $('#birthday_selected').val('1')
        }

        $('#birthday_selected').valid()
    },

    onEmailChange : function () {
        if (('' != $("#emailnameinput").val()) && ('' != $("#emailserverinput").val())) {
            $('#reg_email').val($('#emailnameinput').val()+'@'+$('#emailserverinput').val())
            $('#reg_email').valid()
        }
    },

    hpShowErrorsHandler : function (errorMap, errorList) {
    /** dont show errors near fields on homepage **/
    },

    hpInvalidHandler : function (form, validator) {
        /** display errors only on submit **/
        var msg = ""
        for (i in validator.errorList) {
            msg += validator.errorList[i].message+"\n"
        }

        setTimeout(function () {
            alert(msg)
        }, 10)
    },

    init : function(form, homepage, disabled, resetBirthDate) {
        var ths = this

        form = $(form)
        homepage = homepage ? true : false
        disabled = disabled ? true : false
        resetBirthDate = resetBirthDate ? true : false

        this._form = form
        this._homepage = homepage
        this._disabled = disabled

        /** try to remove top login form **/
        try{
            $("#topLoginForm").remove()
        } catch (err) {

        }

        if (disabled) {
            form.find("select, input").attr("disabled", true)
        } else {

            $.extend($.validator.messages, {
                required: "Buranın yazılması zorunludur",
                email: "Geçerli bir eposta adresi yazınız"
            })


            $.validator.addMethod("username", function(value, element) {
                return value.match(/^[a-z\_IİÖÜÇĞŞıiöüçğş0-9]{4,32}$/i)
            })

            $.validator.addMethod("datusername", function(value, element) {
                var digits = value.match(/[0-9]/gi)
                return (!digits || digits.length <=4)
            })

            form.validate({

                invalidHandler : function (form, validator) {
                    if (ths._homepage) {
                        ths.hpInvalidHandler(form, validator)
                    }
                },

                showErrors: function(errorMap, errorList) {
                    if (ths._homepage) {
                        ths.hpShowErrorsHandler(errorMap, errorList)
                    } else {
                        this.defaultShowErrors()
                    }
                },
                rules: {
                    reg_username: {
                        required: true,
                        minlength: 4,
                        username: true,
                        datusername: true,
                        remote: "/users/checkRegLoginExistence"
                    },
                    reg_password: {
                        required: true,
                        minlength: 5,
                        maxlength: 20
                    },
                    reg_gender:  {
                        required: true
                    },
                    reg_email: {
                        required: true,
                        email: true,
                        remote: "/users/checkRegEmailExistence"
                    },
                    birthday_selected: {
                        required: true
                    },
                    reg_agree: {
                        required: true
                    }
                },
                messages: {
                    reg_username: {
                        required: "Kullanıcı adını giriniz",
                        minlength: "Rumuz çok kısa",
                        username: "Rumuzunuz geçersiz harfler içeriyor",
                        datusername: "Rumuzunuz 4 taneden fazla rakam içeremez",
                        remote: jQuery.validator.format("bu isimle bir kullanıcı zaten mevcut")
                    },
                    reg_password: {
                        required: "Şifre adını giriniz",
                        minlength: "Şifreniz en az 5 karakter uzunluğunda olmalıdır",
                        maxlength: "Şifreniz 20 karakter uzunluğunda maksimum olmalıdır"
                    //				    remote: jQuery.validator.format("Şifreniz sadece rakamlardan oluşamaz. En az 1 harf içermelidir.")
                    },
                    reg_gender: {
                        required: "Cinsiyetinizi seçiniz"
                    },
                    reg_email: {
                        required: "Geçerli bir eposta adresi yazınız",
                        remote: jQuery.validator.format("Eposta adresi geçersiz veya zaten kullanılıyor")
                    },
                    reg_country: {
                        required: "Ülkenizi seçiniz"
                    },
                    reg_city: {
                        required: "Şehirinizi seçiniz"
                    },
                    reg_birthdateYear: {
                        required: "Doğduğunuz yılı seçiniz"
                    },
                    reg_birthdateMonth: {
                        required: "Doğduğunuz ayı seçiniz"
                    },
                    reg_birthdateDay: {
                        required: "Doğduğunuz günü seçiniz"
                    },
                    birthday_selected: {
                        required: "Doğum tarihinizi giriniz"
                    },
                    reg_agree : {
                        required: "Kutucuğu işaretlemelisiniz"
                    }
                },
                onkeyup : false /*function(element) {
                    if (!this.checkable(element)
                        && (element.name in this.submitted || !this.optional(element)) ) {
                        this.element(element)
                    }
                }*/
            })

            if (resetBirthDate) {
                ths.onBirthDateChange()
            }

            ths.onCountryChange()

            $('#reg_gender').change(function() {
                alert('Cinsiyet kayıt sonrası değiştirilemez.')
            })

            $("#inputdropdown").click(function () {
                $(".innersambas").toggle()
            })

            $("#emailserverinput").focus(function () {
                $(".innersambas").show()
            })

            $("#emailserverinput").blur(function () {
                setTimeout("$('.innersambas').hide()", 600)
            })

            $(".mailserver").click(function () {
                $("#emailserverinput").val($(this).text())
                $(".innersambas").hide()
                ths.onEmailChange()
            })

            $("#emailnameinput").change(function () {
                ths.onEmailChange()
            })

            $("#emailserverinput").change(function () {
                ths.onEmailChange()
            })

            $('#reg_birthdateYear').change(function() {
                ths.onBirthDateChange()
            })

            $('#reg_birthdateMonth').change(function() {
                ths.onBirthDateChange()
            })

            $('#reg_birthdateDay').change(function() {
                ths.onBirthDateChange()
            })

            $('#reg_country').change(function() {
                ths.onCountryChange()
            })
        }
    }
}

function limitChars(textid, limit, infodiv) {
    var text = $('#'+textid).val()
    var textlength = text.length
    if (textlength > limit) {
        $('#' + infodiv).html('En fazla '+limit+' karakter!')
        $('#'+textid).val(text.substr(0,limit))
        return false
    } else {
        var left = limit - textlength
        if (left == 0) {
            left='<strong style="color:red">0</strong>'
        }
        $('#' + infodiv).html('Kalan '+ left +' karakter ')
        return true
    }
}

function masker(el, value) {
    $(el).addClass('maska-zorro')
    $(el).val(value)
    $(el).bind('focus',function(){
        if (value == $(this).val()) {
            $(this).removeClass('maska-zorro')
            $(this).val('')
        }
    })
    $(el).bind('blur',function(){
        if ('' == $(this).val()) {
            $(this).addClass('maska-zorro')
            $(this).val(value)
        }
    })
}