﻿///<reference path="jquery-1.3.2-vsdoc2.js" />
var rndJqueryServiceName;

///JQuery'in başlangıç noktasıdır.
///Sayfa'da JQuery'i kullanılırsa DOM hazır olduğunda bu fonksiyonlar çağrılır.
$(document).ready(function() {
    rndJqueryServiceName = jQuery.url.attr("protocol") + "://" + jQuery.url.attr("host") + "/RndJqueryService.svc/";
    if (jQuery.url.attr("host") == "localhost")
        rndJqueryServiceName = jQuery.url.attr("protocol") + "://" + jQuery.url.attr("host") + "/ETClient2008/RndJqueryService.svc/";
    //Ajax ve jQuery çakışmasını engelle    
    PreventConflictBetweenAjaxAndJquery();
    //Sadece rakam girilmesini sağla
    InsertOnlyNumberIntoTextbox();
    //Maxlength'den daha fazla karakter girilmesini engelle
    PreventMoreCharacterThanMaxLength();
});

///Joe Doe - 20.01.2010
///Sayfada number=true olarak attribute verilen textboxlara sadece numara girilebilir.
function InsertOnlyNumberIntoTextbox() {
    $('input[number=true]').keypress(function(e) {
        return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
    });
}

///jQuery kullanılan sayfa da Ajax Control Toolkit de kullanılırsa Jquery çalışmamaya başlıyor.
///Bunu engellemek için bu fonksiyon kullanılmalıdır.
function PreventConflictBetweenAjaxAndJquery() {
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(EndRequestHandler);
    prm.add_beginRequest(BeginRequestHandler);
}

///Ajax Control Toolkit çakışmasını engellemek yazılan fonksiyonlar.
function BeginRequestHandler(sender, args) {

}

function EndRequestHandler(sender, args) {
    InsertOnlyNumberIntoTextbox();
    PreventMoreCharacterThanMaxLength();
}

///Joe Doe - 18/02/2010
///Üye kayıt sayfasında evlilik statüsü değiştirildiğinde Evlilik Tarihi Panelini açar veya kapar.
function ChangedMarialStatus(sender, pnlLbl, pnlDdl) {
    if ($("#" + sender).val() == "Married") {
        $("#" + pnlLbl).show();
        $("#" + pnlDdl).show();
    }
    else {
        $("#" + pnlLbl).hide();
        $("#" + pnlDdl).hide();
    }
}

///Joe Doe - 18/02/2010
///Üye kayıt sayfasında şehir değiştirildiğinde Telefon
function ChangedPhoneNumber(sender, target) {
    var deger = $("#" + sender).val();
    var phoneCode = $("#" + sender + " option[value='" + deger + "']").attr('phonecode');
    $("#" + target).html("+90-(" + phoneCode + ")");
}

//Joe Doe
//15.02.2010 - Pazartesi - 09:28
//FirmID'si 38 olan firmada DepartmantList'de Açılan Childların Renkleri Mavi; Diğer üyeler siyah yapılmalı.
function ColumbiaDepartmentList() {
    var subsubHas = $("#departmentList a[subsub=true]").html();
    var subHas = $("#departmentList a[sub=true]").html();
    var mainHas = $("#departmentList a[main=true]").html();

    if (subsubHas != null) {
        $("#departmentList a[subsub=true]").parent().removeClass();
        $("#departmentList a[subsub=true]").parent().addClass("child");
        $("#departmentList a[sub=true]").parent().removeClass();
        $("#departmentList a[sub=true]").parent().addClass("theother");
        $("#departmentList a[sub=true]").parent().css("margin-left", "15px");
        $("#departmentList a[main=true]").parent().removeClass();
        $("#departmentList a[main=true]").parent().addClass("theother");
    }
    else if (subHas != null) {
        $("#departmentList a[sub=true]").parent().removeClass();
        $("#departmentList a[sub=true]").parent().addClass("child");
        $("#departmentList a[main=true]").parent().removeClass();
        $("#departmentList a[main=true]").parent().addClass("theother");
    }
    else {
        $("#departmentList a[main=true]").parent().removeClass();
        $("#departmentList a[main=true]").parent().addClass("child");
    }
}

///Joe Doe - 19/02/2010
///
///textbox veya textarea ya attribute olarak maxlength verilir.
///maxlength'den daha fazla karakter girilmesi engellenmiş olunur.
function PreventMoreCharacterThanMaxLength() {
    $("textarea[maxlength]").keypress(function(event) {

        var key = event.which;

        //all keys including return.
        if (key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;
            if (length >= maxLength) {

                event.preventDefault();
            }
        }
    });

    $("input[maxlength]").keypress(function(event) {

        var key = event.which;

        //all keys including return.
        if (key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;
            if (length >= maxLength) {

                event.preventDefault();
            }
        }
    });
}

///Joe Doe - 24/02/2010
///FirmID'si 39 olan firmada 'de Department/ShowAllProducts.aspx sayfasında sol tarafta çıkan ProductFilter kontrolu için yazıldı.
///Filtreleme işlemleri için. Ajax ile veri istenip sol tarafta gösterme işlemi.
//{"size":["L","M","S","XXS"],"length":["28","27","25","34"],"waist":["40","48","49","50"],"color":["Kırmızı","Mavi","Yeşil","Mürekkep"]}
var jsonResultStart = '{';

var jsonSizeStart = '"size":[';
var jsonSize = '';
var jsonSizeEnd = ']';

var jsonLengthStart = '"length":[';
var jsonLength = '';
var jsonLengthEnd = ']';

var jsonWaistStart = '"waist":[';
var jsonWaist = '';
var jsonWaistEnd = ']';

var jsonColorStart = '"color":[';
var jsonColor = '';
var jsonColorEnd = ']';

var jsonMoneyStart = '"money":[';
var jsonMoney = '';
var jsonMoneyEnd = ']';

var jsonResultEnd = '}';
var effectDuration = 300;
var requestAfterWaitTime = 1000;
var timer;
var sections = { "size": 0, "waist": 1, "length": 2, "color": 3, "money": 4, "reset": 5 };

function BindOnClickMethodForProductFilter() {
    $(".product_feature .beden li").click(function() {
        MakeInvisibleRequestDataByAjaxAndMakeVisible(sections.size, $(this));
    });

    $(".product_feature .boy li").click(function() {
        MakeInvisibleRequestDataByAjaxAndMakeVisible(sections.length, $(this));
    });

    $(".product_feature .bel li").click(function() {
        MakeInvisibleRequestDataByAjaxAndMakeVisible(sections.waist, $(this));
    });

    $(".product_feature .renk li").click(function() {
        MakeInvisibleRequestDataByAjaxAndMakeVisible(sections.color, $(this));
    });

    //ProductFilter.ascx kontrolunde Reset tuşu için aşağıdaki kod bloğu yazıldı.
    $("#" + GetIdOfResetButton()).click(function() {
        MakeInvisibleRequestDataByAjaxAndMakeVisible(sections.reset, $(this));
    });
}


function GetMoneySliderValueWhenChanging(event, ui) {
    $("#amount").html(ui.values[0] + ' TL - ' + ui.values[1] + ' TL');

    MakeInvisibleRequestDataByAjaxAndMakeVisible(sections.money, ui);
}

function MakeInvisibleRequestDataByAjaxAndMakeVisible(choice, element) {
    if (choice != 5 && choice != 4)
        element.toggleClass("selected");

    var size = "";
    if (choice != 4)
        size = element.attr("size");

    $("#" + GetIdOfPnlListProductCustom()).fadeTo(effectDuration, 0, function() {
        $("#" + GetIdOfPnlListProductCustom()).html("<div id='loading' style='margin-left: 15px; margin-top: 15px; display: inline; width: 100%;text-align:center;'><img src=\"../../media/img_general/loading.gif\" width=\"90px\" height=\"90px\" /></div>");
        $("#" + GetIdOfPnlListProductCustom()).css("opacity", "1.0");

        //içeriği temizle
        //        $("#loading").show("fast");
        switch (choice) {
            case 0:
                {
                    var index = jsonSize.indexOf('"' + size + '",', 0);

                    if (index < 0)
                        jsonSize += '"' + size + '",';
                    else
                        jsonSize = jsonSize.replace('"' + size + '",', '');
                    break;
                }
            case 1:
                {
                    //Seçilen li'nin değerini bir diziye al.                        
                    var index = jsonWaist.indexOf('"' + size + '",', 0);

                    if (index < 0)
                        jsonWaist += '"' + size + '",';
                    else
                        jsonWaist = jsonWaist.replace('"' + size + '",', '');
                    break;
                }
            case 2:
                {
                    var index = jsonLength.indexOf('"' + size + '",', 0);

                    if (index < 0)
                        jsonLength += '"' + size + '",';
                    else
                        jsonLength = jsonLength.replace('"' + size + '",', '');
                    break;
                }
            case 3:
                {
                    var index = jsonColor.indexOf('"' + size + '",', 0);

                    if (index < 0)
                        jsonColor += '"' + size + '",';
                    else
                        jsonColor = jsonColor.replace('"' + size + '",', '');
                    break;
                }
            case 4:
                {
                    jsonMoney = '"' + element.values[0] + '","' + element.values[1] + '"';
                    break;
                }
            case 5:
                {
                    jsonSize = '';
                    jsonLength = '';
                    jsonWaist = '';
                    jsonColor = '';
                    jsonMoney = '';

                    //Slider'ı baslangıc konumuna taşı.
                    var max = $("#slider-range").slider('option', 'max');
                    var min = $("#slider-range").slider('option', 'min');

                    $("#slider-range").slider('option', 'values', [min, max]);

                    $("#amount").html(min + ' TL - ' + max + ' TL');

                    //seçili olanları alır selected olanları kaldırır.
                    $(".selected").toggleClass("selected");
                    break;
                }
        }
        //Sağ tarafta yer alan Div'i görünüş olarak kaybet. Ajax ile istekde bulun.  Gelen HTML'i sayfaya yazdır.
        //requestAfterWaitTime süresi sonunda istek gönder.
        window.clearTimeout(timer);
        timer = window.setTimeout(GetAndSetDataForFilter, requestAfterWaitTime);
    });
}

function GetAndSetDataForFilter() {
    $.ajax({
        url: rndJqueryServiceName + "GetProductsByFilter",
        type: "POST",
        contentType: "application/json",
        data: jsonResultStart + jsonSizeStart + jsonSize.substring(0, jsonSize.length - 1) + jsonSizeEnd + ',' +
                jsonLengthStart + jsonLength.substring(0, jsonLength.length - 1) + jsonLengthEnd + ',' +
                jsonWaistStart + jsonWaist.substring(0, jsonWaist.length - 1) + jsonWaistEnd + ',' +
                jsonColorStart + jsonColor.substring(0, jsonColor.length - 1) + jsonColorEnd + ',' +
                jsonMoneyStart + jsonMoney + jsonMoneyEnd +
                ',"departmentId":' + GetDepartmentID() + jsonResultEnd,
        dataType: "json",
        success: function(data) {
            $("#" + GetIdOfPnlListProductCustom()).fadeTo(effectDuration, 1.0, function() {
                $("#" + GetIdOfPnlListProductCustom()).html(data.GetProductsByFilterResult);
            });
        },
        error: function(xhr, ajaxOptions, thrownError) {
            if (xhr.status == "500")
                $('#one').jGrowl('Hata Oluştu!Kısa Süre Sonra Tekrar Deneyiniz.');
            else
                $('#one').jGrowl('Bağlantınızda Sorun Oluştu!Kısa Süre Sonra Tekrar Deneyiniz.');
            MessageEffect("Ürün Eklenemedi!");
        }
    });
}