﻿///<reference path="jqueryPlugin/jquery-1.4.1.min-vsdoc.js" />
var rndJqueryServiceName;
var rndMainPath;
var currentPage;

///JQuery'in başlangıç noktasıdır.
$(document).ready(function () {

    try {
        currentPage = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
        rndJqueryServiceName = location.protocol + "//" + location.hostname + "/RndJqueryService.svc/";
        rndMainPath = location.protocol + "//" + location.hostname + "/";
        if (location.hostname == "localhost") {
            rndJqueryServiceName = location.protocol + "//" + location.hostname + "/ETAsports2011/RndJqueryService.svc/";
            rndMainPath = location.protocol + "//" + location.hostname + "/ETAsports2011/";
        }
    }
    catch (err) { }

    // ürün detay popup için
    var isLink = $('input[id="detailLink"]').val();
    if (isLink == "False" || isLink == undefined) {
        $('a[id$=detailLink]').click(newTopicModal);
    }

    //Ana Sayfa Aradığını Bul Menüsü için
    $(".pSeacrh-Button a").click(function () {

        sMark = $("#selectBoxScroller3 ul").children("li.selected").text();
        sGender = $("#selectBoxScroller2 ul").children("li.selected").text();
        sCategory = $("#selectBoxScroller1 ul").children("li.selected").text();


        if (sCategory == "LÜTFEN SEÇİM YAPINIZ" || sGender == "LÜTFEN SEÇİM YAPINIZ" || sMark == "LÜTFEN SEÇİM YAPINIZ") {
            //window.location = rndMainPath + "?error search";
            $("#lblError").show();
            return false;
        }

        else {

            depId = 8;
            pageName = "Converse";

            if (sMark == "CONVERSE") {
                pageName = "Converse";
                if (sGender == "ERKEK") {
                    depId = 8; pageName = "Erkek";
                    if (sCategory == "AYAKKABI") { depId = 8; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 17; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 62; pageName = "Aksesuar"; }
                }
                else if (sGender == "KADIN") {
                    depId = 7; pageName = "Kadin";
                    if (sCategory == "AYAKKABI") { depId = 7; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 11; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 62; pageName = "Aksesuar"; }
                }
                else if (sGender == "ÇOCUK") {
                    depId = 9; pageName = "Cocuk";
                    if (sCategory == "AYAKKABI") { depId = 9; pageName = "Cocuk"; }
                    else if (sCategory == "AKSESUAR") { depId = 64; pageName = "Canta"; }
                }
                else {
                    depId = 8;
                    if (sCategory == "AYAKKABI") { depId = 8; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 10; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 62; pageName = "Aksesuar"; }
                }
            }
            else if (sMark == "COLUMBİA") {
                pageName = "Columbia";
                if (sGender == "ERKEK") {
                    depId = 81; pageName = "Erkek";
                    if (sCategory == "AYAKKABI") { depId = 79; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 137; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 83; pageName = "Aksesuar"; }
                }
                else if (sGender == "KADIN") {
                    depId = 80; pageName = "Kadin";
                    if (sCategory == "AYAKKABI") { depId = 80; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 137; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 83; }
                }
                else {
                    depId = 79;
                    if (sCategory == "AYAKKABI") { depId = 79; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 137; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 83; pageName = "Aksesuar"; }
                }
            }
            else {
                if (sGender == "ERKEK") {
                    depId = 8; pageName = "Erkek";
                    if (sCategory == "AYAKKABI") { depId = 8; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 17; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 62; pageName = "Aksesuar"; }
                }
                else if (sGender == "KADIN") {
                    depId = 7; pageName = "Kadin";
                    if (sCategory == "AYAKKABI") { depId = 7; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 11; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 62; pageName = "Aksesuar"; }
                }
                else {
                    depId = 8; pageName = "Converse";
                    if (sCategory == "AYAKKABI") { depId = 6; pageName = "Ayakkabi"; }
                    else if (sCategory == "TEKSTİL") { depId = 10; pageName = "Tekstil"; }
                    else if (sCategory == "AKSESUAR") { depId = 62; pageName = "Aksesuar"; }
                }
            }

            window.location = rndMainPath + "Departman/" + depId + "/" + pageName + ".aspx";
        }
    });

    $('a[id$=hlnSizeTable]').click(newSizeTableModal);

    $("input[numeric=true]").keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;
        // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
        if (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105)) {
            return true;
        }
        else
            return false;
    });
    $("input[numeric=true]").keyup(function (e) {
        minValue = $(this).attr("minValue");
        maxValue = $(this).attr("maxValue");
        if (minValue != null) {
            if (parseInt($(this).val()) < minValue)
                $(this).val(minValue);
        }

        if (maxValue != null) {
            if (parseInt($(this).val()) > maxValue)
                $(this).val(maxValue);
        }
    });

    /////////////////////////////////////////////////////////////////
    ///SiteMessage gösterim efekti          
    $("#divSiteMessage").not(".invisible").fadeIn("slow");

    //////////////////////////////////////////////////////////////////
    /// SiteMessage üzerine tıklandığında sitemessage'ın kapanması 
    $("#divSiteMessage").click(function () {
        $("#divSiteMessage").fadeOut(1000);
    });

    //////////////////////////////////////////////////////////////////
    ///Share Link
    $("a[facebookshare=true]").attr("href", "http://www.facebook.com/share.php?u=" + self.location.href);
    $("a[twittershare=true]").attr("href", "http://twitter.com/home?status=" + self.location.href);
    $("a[friendFeedshare=true]").attr("href", "http://friendfeed.com/?url=" + self.location.href);

    $("a[facebookshare=true]").attr("target", "_blank");
    $("a[twittershare=true]").attr("target", "_blank");
    $("a[friendFeedshare=true]").attr("target", "_blank");

    /*$(this).parent().parent().attr("class") == "Paylas"*/
    $(".paylas a").click(function () {
        if ($(this).attr("id") != "hlnProductSuggestion" && $(this).attr("id") != "hlnAddFavourite") {
            window.open($(this).attr("href"), "Xman", "width=800, height=600");
        }
        return false;
    });

    //////////////////////////////////////////////////////////////////
    ///Autocomplete
    $("body").click(function () { $("#searchResult").hide(); });
    $('[search_field=true]').keyup(function (e) {
        var key = e.charCode || e.keyCode || 0;
        str = jQuery.trim($('[search_field=true]').val());
        if ((key != 13 && key != 40 && key != 38 && key != 27) && str.length > 2) {
            $.ajax({
                url: rndJqueryServiceName + "SearchProduct",
                type: "POST",
                contentType: "application/json",
                data: '{"q":"' + jQuery.trim($('[search_field=true]').val()) + '"}',
                dataType: "json",
                complete: function () {

                },
                success: function (data) {
                    $("#searchResult").text("");
                    if (data != null && data["SearchProductResult"] != null && data["SearchProductResult"].length > 0) {
                        var searchResult = "";
                        for (var i = 0; i < data["SearchProductResult"].length; i++) {
                            searchResult += '<div class="satir" selecteditem="false" style="width:92%; height:12px; padding:5px;">' +
                                        '<a onclick="searchItemSelect(this)" depId="' + data["SearchProductResult"][i]["DepartmentId"] + '" tagName="' + data["SearchProductResult"][i]["TagName"] + '" href="#"><div word="true" style="float: left;">' +
                                            data["SearchProductResult"][i]["TagName"] +
                                        '</div>' +
                                        '<div style="float: right;">' +
                                             data["SearchProductResult"][i]["DepartmentName"] +
                                        '</div><div style="display:none;" department="true">' + data["SearchProductResult"][i]["DepartmentId"] + '</div></a></div>';
                        }
                        $("#searchResult").append(searchResult);
                        $("#searchResult").show();
                    }
                    else {
                        $("#searchResult").hide();
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {

                }
            });
        }

    });

    $('[search_field=true]').keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;
        //Down
        if (key == 40) {
            if ($("#searchResult").find("div[selecteditem=true]:first").attr("class") != null) {
                //Sıra Alma
                sira = $("#searchResult").find("div[selecteditem=true]:first");

                //Temizleme 
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").attr("selecteditem", "false");
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").css("background-color", "#eeeeee");

                $(sira).next().attr("selecteditem", "true");
                $(sira).next().css("background-color", "#ffffff");
            }
            else {

                //Temizleme 
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").attr("selecteditem", "false");
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").css("background-color", "#eeeeee");

                $("#searchResult").find("div[selecteditem=false]:first").css("background-color", "#ffffff");
                $("#searchResult").find("div[selecteditem=false]:first").attr("selecteditem", "true");
            }
        }
        //Up
        else if (key == 38) {
            if ($("#searchResult").find("div[selecteditem=true]:first").attr("class") != null) {
                //Sıra Alma
                sira = $("#searchResult").find("div[selecteditem=true]:first");

                //Temizleme 
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").attr("selecteditem", "false");
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").css("background-color", "#eeeeee");

                $(sira).prev().css("background-color", "#ffffff");
                $(sira).prev().attr("selecteditem", "true");
            }
            else {
                //Temizleme 
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").attr("selecteditem", "false");
                $("#searchResult").find("div[selecteditem=true],div[selecteditem=false]").css("background-color", "#eeeeee");

                $("#searchResult").find("div[selecteditem=false]:first").css("background-color", "#ffffff");
                $("#searchResult").find("div[selecteditem=false]:first").attr("selecteditem", "true");
            }
        }
        //Enter Key
        else if (key == 13) {
            if ($("#searchResult").find("div[selecteditem=true]:first").attr("class") != null) {
                var str = $("#searchResult").find("div[selecteditem=true]:first").find("div[word=true]:first").text();
                var depId = $("#searchResult").find("div[selecteditem=true]:first").find("div[department=true]:first").text();
                $('[search_field=true]:first').val(str);
                alert($('[search_field=true]:first').val(str));
                window.location = rndMainPath + "UrunArama.aspx?searchText=" + str + "&depId=" + depId + "&filter=#";
                return false;
            }
            else {
                if (jQuery.trim($('[search_field=true]:first').val()).length > 0) {
                    window.location = rndMainPath + "UrunArama.aspx?searchText=" + $('input[search_field=true]:first').val() + "&filter=#";
                }
            }
        }
        //Esc Key
        else if (key == 27) {
            $("#searchResult").hide();
        }
    });
    //Close Autocomplete
    $("#searchResult").blur(function () {
        $($("#searchResult")).oneTime(4000, function () {
            $("#searchResult").hide();
        });
    });

    //////////////////////////////////////////////////////////////////////////////////////////////
    /// Açılışta sayfadaki tum ceksbaksların eşleşen checkboxlarla aynı değerde olmasını sağla ///
    //////////////////////////////////////////////////////////////////////////////////////////////
    if ($("input[type=checkbox]").size() > 0) {
        if (($("input[type=checkbox]").size() == $("div.unselected").size()) || ($("input[type=checkbox]").size() == $("div.selected").size())) {
            $("input[type=checkbox]").each(function () {
                thisChk = $.fn.GetOuterCheckbox($(this));
                $(thisChk).attr("class", ($(this).attr("checked") == true) ? "selected" : "unselected");
            });
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
    //////////// Sayfalarda olabilecek detay linklerine popup açma fonksiyonu ekler //////////////
    //////////////////////////////////////////////////////////////////////////////////////////////
    if ($("a[id$=detailLink]").size() > 0) {
        $("a[id$=detailLink]").click(function () {
            DetailPopupState(true, this)
        });
        $('a[id$=detailLink]').attr("style", "cursor: pointer");
    }


    /////////////////////////////////////////////////////////////////////////////////////////////////
    //////////// Masterda bulunan popup modal //////////////
    //////////////////////////////////////////////////////////////////////////////////////////////
    //When you click on a link with class of poplight and the href starts with a # 
    $('a.poplight[href^=#]').click(function () {
        var popID = $(this).attr('rel'); //Get Popup Name
        var popURL = $(this).attr('href'); //Get Popup href to define size

        //Pull Query & Variables from href URL
        var query = popURL.split('?');
        var dim = query[1].split('&');
        var popWidth = dim[0].split('=')[1]; //Gets the first query string value

        //Fade in the Popup and add close button
        $('#' + popID).fadeIn().css({ 'width': Number(popWidth) }).prepend('<a href="#" class="close"><img src="../../media/img_shared/close-pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');

        //Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
        var popMargTop = ($('#' + popID).height() + 80) / 2;
        var popMargLeft = ($('#' + popID).width() + 80) / 2;

        //Apply Margin to Popup
        $('#' + popID).css({
            'margin-top': -popMargTop,
            'margin-left': -popMargLeft
        });

        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer 

        return false;
    });


    //Close Popups and Fade Layer
    $('a.close, #fade').live('click', function () { //When clicking on the close or fade layer...
        $('#fade , .popup_block').fadeOut(function () {
            $('#fade, a.close').remove();
        }); //fade them both out

        return false;
    });
});

function SearchRequest() {
    if ($("#searchResult").find("div[selecteditem=true]:first").attr("class") != null) {
        var str = $("#searchResult").find("div[selecteditem=true]:first").find("div[word=true]").text();
        var depId = $("#searchResult").find("div[selecteditem=true]:first").find("div[department=true]").text();

        $('[search_field=true]:first').val(str);
        window.location = rndMainPath + "UrunArama.aspx?searchText=" + escape(str) + "&depId=" + depId + "&filter=#";
        return false;
    }
    else {
        if (jQuery.trim($('[search_field=true]:first').val()).length > 0) {
            window.location = rndMainPath + "UrunArama.aspx?searchText=" + escape($('input[search_field=true]:first').val()) + "&filter=#";
        }
    }
}

//Autocomplete Selected Item
function searchItemSelect(obj) {
    var str = $(obj).find("div[word=true]:first").text();
    var depId = $(obj).find("div[department=true]:first").text();

    alert(str);

    $('[search_field=true]').val(str);
    window.location = rndMainPath + "UrunArama.aspx?searchText=" + escape(str) + "&depId=" + depId + "&filter=#";
}



/////////////////////////////////////////////////////////////////////
///////TextboxEfekt
var tSearch = "Ürün numarası,ürün tipi,marka..vb";
var tEmail = "e-mail adresinizi yazınız";
var tDiscountCoupon = "Promosyon Kodu Giriniz";

function MakeEmpty(TextBox) {
    if (TextBox == "search") {
        if ($("input[search=true]").val() == tSearch) {
            $("input[search=true]").val("");
        }
    }

    if (TextBox == "email") {
        if ($("input[email=true]").val() == tEmail) {
            $("input[email=true]").val("");
        }
    }
}

function IsEmpty(Textbox) {
    if (Textbox == "search") {
        if ($("input[search=true]").val() == "")
            $("input[search=true]").val(tSearch);
    }
    emailTemp = "";
    if (Textbox == "email") {
        $("input[email=true]").each(function (index) {
            if ($(this).val() != "") {
                emailTemp = $(this).val();
            }
        });

        if (emailTemp == "") {
            $("input[email=true]").each(function (index) {
                $(this).val(tEmail);
            });
        }
    }
    if (Textbox == "discountCouponNumber") {
        if ($("#discountCouponNumber").val() == "")
            $("#discountCouponNumber").val(tDiscountCoupon);
    }
}
////////////////////////////////////////////////////////////////////
///Resim Yükleme 
function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}
////////////////////////////////////////////////////////////////////
///Üye Girişi Validation
$("#btnSignup").click(function () {
    if ($("#ddlBirthdayDay").val() == -1 || $("#ddlBirthdayMonth").val() == -1 || $("#ddlBirthdayYear").val() == -1) {
        $("#lblSignupError").text("Lütfen ay, gün ve yıl girdiğinizden emin olunuz.");
        return false;
    }
    else
    { $("#lblSignupError").text(""); }
});
///////////////////////////////////////////////////////////////////
/// Fatura & Teslimat Adres seçimleri div ve checkbox işlemleri ///
/////////////////////////////////////////////////////////////////// 
var list; var thisIdIndex;
$(function () {

    $("input[id$=chkSelectAddress]:first").click(function () {
        $(this).attr("checked", !$(this).attr("checked"));
    });

    $(".adres_left, .adres_right").click(function () {
        $.fn.ToggleAddressSelection($(this).parent().children(".adres_right").children(".invisible").children("input"));
    });

    $.fn.ToggleAddressSelection = function (x) {
        if ($(x).attr("checked") == true) {
            $(x).attr("checked", false);
            $.fn.ToggleChecked($(x).parent().next("div"), "unselected");
        }
        else {
            $(".adresler .adres_right").find("[type=checkbox]").attr("checked", false);
            $(".adresler .adres_right").find("[class=selected]").attr("class", "unselected");
            $(x).attr("checked", true);
            $.fn.ToggleChecked($(x).parent().next("div"), "selected");
        }
        list = $("input[id$=chkSelectAddress]:first");
        var thisId = $(x).attr("id");
        for (var i = 0; i < list.length; i++)
            if (list[i].id == thisId)
                thisIdIndex = i;
        list.splice(thisIdIndex, 1);

        for (var i = 0; i < list.length; i++) {
            if ($(list[i]).attr("checked") == true)
                $.fn.ToggleChecked($(list[i]).parent().next("div"), "unselected");
            $(list[i]).removeAttr("checked");
        }
    }

    $.fn.ToggleChecked = function (obj, state) {
        $(obj).stop(true).animate({ opacity: 0 }, "fast", "linear", function () {
            $(this).attr("class", state);
            $(this).animate({ opacity: 1 }, "fast");
        });
    }
});
///////////////////////////////////////////////////////////////////
///        AcceptPurchase.aspx div ve checkbox işlemleri        ///
///////////////////////////////////////////////////////////////////
$(function () {
    $("div#havale").click(function () {
        HavaleClick(this);
    });
});

///////////////////////////////////////////////////////////////////
///            Checkbox ile eşlenmiş ceksbaksı döndür           ///
///////////////////////////////////////////////////////////////////
$.fn.GetOuterCheckbox = function (x) {
    return $(x).parent().next();
}

///////////////////////////////////////////////////////////////////
///              Genel checkbox animasyonları                   ///
///////////////////////////////////////////////////////////////////
$(function () {
    $("div[class=unselected], div[class=selected]").click(function (e) {
        //Disable alan tetiklenmez.
        if ($(this).parent().parent().attr("disabled") == "disabled")
            return false;
        //Eğer çekboks havale divinin içindeyse (AcceptPurchase.aspx)
        if ($(this).prev("input").attr("id") == "rbAccount")
            return;
        else if ($(this).prev("input").attr("id") == "rbInstalment")
            return;
        else if ($(this).prev().children("input[id$=chkSelectAddress]").size() > 0)
            return;
        else
            ClickEvent(this);
    });

    $("span[type=checkboxTrigger]").click(function () {
        $(this).prev("div").click();
    });

    $("tr[type=checkboxTrigger]").click(function (e) {
        //Disable alan tetiklenmez.
        if ($(this).attr("disabled") == "disabled")
            return false;

        tObj = $(this).find("#rbInstalment").parent().find("span");
        selectInstallment($(tObj).attr("price"), $(tObj).attr("value"));
        ClickEvent(this);
    });
});

function selectInstallment(price, inst) {
    document.getElementById("hddInstalmentCount").value = inst;
    document.getElementById("ctl00_ctl00_MainContent_SaleContentPlace_HiddenTotalPrice").value = price;
    $("#ctl00_ctl00_MainContent_SaleContentPlace_lblTotalPrice").text(ConvertToMoney(price.replace(".", ",").replace(" TL", "")));  // + " TL"
}

function HavaleClick(container) {
    selectAccount($(container).find("input[id=rbAccount]").attr("value"));
    $(container).find("input[id=rbAccount]").attr("checked", true);
    $.fn.ToggleChecked($("div.selected"), "unselected");
    $.fn.ToggleChecked($(container).children(".form").find("input[id=rbAccount]").next("div"), "selected");
}

function ClickEvent(obj) {
    chk = obj;

    if ($(chk).attr("type") == "checkboxTrigger")
        chk = $(chk).find("div[class$=selected]");
    checkedStatus = $(chk).attr("class");

    if ($(chk).attr("group") != "") {
        $.fn.ToggleChecked($("div.selected").filter('[group=' + $(chk).attr("group") + ']'), "unselected");
        $("div.selected").filter('[group=' + $(chk).attr("group") + ']').prev("span").find("input").attr("checked", false);
    }
    else
        $.fn.ToggleChecked($("div.selected"), "unselected");

    if (checkedStatus == "unselected") {
        $.fn.ToggleChecked($(chk), "selected");
        $(chk).prev("span").find("input").attr("checked", true);
    }
    else
        $(chk).prev("span").find("input").attr("checked", false);

    $(chk).prev("span").find("input[type=checkbox]").click();

    if (checkedStatus == "unselected")
        $(chk).prev("span").find("input").attr("checked", true);
    else
        $(chk).prev("span").find("input").attr("checked", false);
}
////////////////////////////////////////
///     SetSiteMessage fonksiyonu    ///
////////////////////////////////////////
$.fn.SetSiteMessage = function (message, status) {
    smClass = "invisible";

    if (status == "Success") smClass = "siteMessageSuccess";
    else if (status == "Error") smClass = "siteMessageError";

    $("#divSiteMessage").text(message).attr("class", smClass).css("display", "none").fadeIn("slow");
}
////////////////////////////////////////////////////////////////////
///Üye Detay Sayfası Control
$("#btnKaydet").click(function () {
    if ($("#ddlBirthdayDay").val() == -1 || $("#ddlBirthdayMonth").val() == -1 || $("#ddlBirthdayYear").val() == -1) {
        $("#lblSuccess").text("Lütfen ay, gün ve yıl girdiğinizden emin olunuz.");
        return false;
    }
    else
    { $("#lblSignupError").text(""); }
});
//////////////////////////////////////////////////////////////////
///Şifremi Değiştir Sayfası Control
$("#btnChangePassword").click(function () {
    if ($("#txtPassOld").val() == "" || $("#txtPassNew").val() == "" || $("#txtPassNewMatch").val() == "") {
        $("#lblError").text("Tüm alanlar doldurulmalıdır.");
        return false;
    }
    else if ($("#txtPassNew").val() != $("#txtPassNewMatch").val()) {
        $("#lblError").text("Girdiğiniz şifreler uyuşmuyor");
        return false;
    }
});

function SizeTablePopupState(value) {
    try {
        if (value) {
            $(".sizeTableModalPopup").show();
        }
        else {
            Boxy.get(".sizeTableModalPopup").hide();
        }
    }
    catch (err) { alert(err); }
}

function newSizeTableModal() {
    new Boxy($(".sizeTableModalPopup"), {
        modal: true, behaviours: function (c) {
            c.find('a:first').click(function () {
                newSizeTableModal();
            });
        }
    });
};



//////////////////////////////////////////////////////////////////
///Arkadaşıma Öner Wcf Gönderim
function ProductSuggestionSend() {
    var productDescriptionID = jQuery.trim($("input[class=productDescriptionId]").val());
    var fromNameSurname = ($("input[fromNameSurname=true]").val() == null) ? "" : $("input[fromNameSurname=true]").val();
    var fromEMail = ($("input[fromEMail=true]").val() == null) ? "" : $("input[fromEMail=true]").val();
    var toNameSurname = $("input[toNameSurname=true]").val();
    var toEMail = $("input[toEMail=true]").val();
    var message = $("textarea[message=true]").val();

    if (validate(toEMail) == false || jQuery.trim(toNameSurname).length == 0 || jQuery.trim(message).length == 0) {
        $("span[productSuggestionValidation=true]").show();
        return false;
    }
    else
        $("span[productSuggestionValidation=true]").hide();

    $(".loading").show();
    $("span[productSuggestionWait=true]").show();
    //    $("span[productSuggestionValidation=true]").hide();
    $("#ProductSuggestionSendResult").remove();
    $("button[id$=BtnProductSuggestionSend]").attr("disabled", "true");

    $.ajax({
        url: rndJqueryServiceName + "ProductSuggestionSend",
        type: "POST",
        contentType: "application/json",
        data: '{"productDescriptionID":"' + productDescriptionID + '","fromNameSurname":"' + fromNameSurname + '","fromEMail":"' + fromEMail + '","toNameSurname":"' + toNameSurname + '","toEMail":"' + toEMail + '","message":"' + message + '"}',
        dataType: "json",
        complete: function () {
            $(".loading").hide();
        },
        success: function (data) {
            if (data["ProductSuggestionSendResult"] == true) {
                //                Boxy.get(".modalPopup").hide();
                $("input[fromNameSurname=true]").val("");
                $("input[fromEMail=true]").val("");
                $("input[toNameSurname=true]").val("");
                $("input[toEMail=true]").val("");
                $("textarea[message=true]").val("");
                ProductSuggestionPopupState(false);
            }
            else {
                $("button[id$=BtnProductSuggestionSend]").removeAttr("disabled");
                $("span[productSuggestionWait=true]").after("<label id='ProductSuggestionSendResult'>Mail Gönderilemedi!</label>");
                MessageEffectToObject($("#ProductSuggestionSendResult"));
                //ProductSuggestionPopupState(false);
            }
            $("span[productSuggestionWait=true]").hide();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (xhr.status == "500")
                $('#one').jGrowl($(".JsCodeErrorMessage").text());
            else
                $('#one').jGrowl($(".JsConnectionErrorMessage").text());
        }
    });
    return false;
}

//////////////////////////////////////////////////////////////////
///Favori Listem Wcf Gönderim
function ShoppingListSend() {
    var toNameSurname = $("input[toNameSurname=true]").val();
    var toEMail = $("input[toEMail=true]").val();
    var message = $("textarea[message=true]").val();

    if (validate(toEMail) == false || jQuery.trim(toNameSurname).length == 0 || jQuery.trim(message).length == 0) {
        $("span[shoppingListValidation=true]").show();
        return false;
    }
    else
        $("span[shoppingListValidation=true]").hide();

    $(".loading").show();
    $("span[shoppingListWait=true]").show();
    //    $("span[productSuggestionValidation=true]").hide();
    $("#ShoppingListSendResult").remove();
    $("button[id$=BtnShoppingListSend]").attr("disabled", "true");

    $.ajax({
        url: rndJqueryServiceName + "ShoppingListSend",
        type: "POST",
        contentType: "application/json",
        data: '{"toNameSurname":"' + toNameSurname + '","toEMail":"' + toEMail + '","message":"' + message + '"}',
        dataType: "json",
        complete: function () {
            $(".loading").hide();
        },
        success: function (data) {
            if (data["ShoppingListSendResult"] == true) {
                //                Boxy.get(".modalPopup").hide();
                $("input[toNameSurname=true]").val("");
                $("input[toEMail=true]").val("");
                $("textarea[message=true]").val("");
                ShoppingListPopupState(false);
            }
            else {
                $("button[id$=BtnShoppingListSend]").removeAttr("disabled");
                $("span[shoppingListWait=true]").after("<label id='ShoppingListSendResult'>Mail Gönderilemedi!</label>");
                MessageEffectToObject($("#ShoppingListSendResult"));
                //ProductSuggestionPopupState(false);
            }
            $("span[shoppingListWait=true]").hide();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (xhr.status == "500")
                $('#one').jGrowl($(".JsCodeErrorMessage").text());
            else
                $('#one').jGrowl($(".JsConnectionErrorMessage").text());
        }
    });
    return false;
}

//////////////////////////////////////////////////////////////////
///Küçük Sepet

$(document).ready(function () {
    //Open Small Basket

    var hoverConfig = { over: OpenSmallBasket, timeout: 400, out: none };

    $(".sepetLink").hoverIntent(hoverConfig);

    function OpenSmallBasket() {
        if ($("#miniCount").text() != "0" && $("#miniCount").text() != " 0 ÜRÜN" && GetOpenSmallBasket()) {
            $(".sepet_acik").stopTime();
            EffectToObject($(".sepet_acik"));
        }
    };

    $(".sepet_acik").mouseover(function () {
        if ($("#miniCount").text() != "0" && $("#miniCount").text() != " 0 ÜRÜN" && GetOpenSmallBasket()) {
            GetLastProductFromBasket();
            $(".sepet_acik").stopTime();
        }
    });
    $(".sepet_acik").mouseout(function () {
        if ($("#miniCount").text() != "0" && $("#miniCount").text() != " 0 ÜRÜN" && GetOpenSmallBasket() && !closeSmallBasketState) {
            $(".sepet_acik").stopTime();
            EffectToObject($(".sepet_acik"));
        }
    });
    $(".sepetLink").mouseover(function () {
        if ($("#miniCount").text() != "0" && $("#miniCount").text() != " 0 ÜRÜN" && GetOpenSmallBasket()) {
            GetLastProductFromBasket();
            $(".sepet_acik").stopTime();
        }
    });
    $(".sepetLink").mouseout(function () {
        if ($("#miniCount").text() != "0" && $("#miniCount").text() != " 0 ÜRÜN" && GetOpenSmallBasket()) {
            $(".sepet_acik").stopTime();
            EffectToObject($(".sepet_acik"));
        }
    });
    //    $(".sepetLink").mouseover(function () {
    //        if ($("#miniCount").text() != "0" && GetOpenSmallBasket()) {
    //            GetLastProductFromBasket();
    //            $(".sepet_acik").stopTime();
    //        }
    //    });
    //    $(".sepetLink").mouseout(function () {
    //        if ($("#miniCount").text() != "0" && GetOpenSmallBasket()) {
    //            $(".sepet_acik").stopTime();
    //            EffectToObject($(".sepet_acik"));
    //        }
    //    });

    //    $(".sepet_acik").mouseover(function () {
    //        if ($("#miniCount").text() != "0") {
    //            $(".sepet_acik").stopTime();
    //            $(".sepet_acik").show();
    //        }
    //    });
    //    $(".sepet_acik").mouseout(function () {
    //        if ($("#miniCount").text() != "0" && !closeSmallBasketState) {
    //            $(".sepet_acik").stopTime();
    //            EffectToObject($(".sepet_acik"));
    //        }
    //    });
});
var smallBasketState = false;
function GetLastProductFromBasket() {
    if (!smallBasketState && $(".sepet_acik").css("display") == "none" && GetOpenSmallBasket()) {
        smallBasketState = true;
        $.ajax({
            url: rndJqueryServiceName + "GetBasket",
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            complete: function () {

            },
            success: function (data) {

                cartString = "";

                if (data != null && data["GetBasketResult"] != null && data["GetBasketResult"]["ProductItems"].length > 0) {

                    productCount = 0;
                    for (var i = 0; i < data["GetBasketResult"]["ProductItems"].length; i++) {
                        productCount += parseInt(data["GetBasketResult"]["ProductItems"][i]["Quantity"]);
                    }

                    //alert(data["GetBasketResult"]["ProductItems"][data["GetBasketResult"]["ProductItems"].length - 1]["ProductName"]);
                    var product = data["GetBasketResult"]["ProductItems"][data["GetBasketResult"]["ProductItems"].length - 1];

                    var productSpecialityItems = "";

                    if (product["ColorSpecName"] != null)
                        productSpecialityItems += " " + product["ColorSpecName"];
                    if (product["FirstSpecName"] != null)
                        productSpecialityItems += "/" + product["FirstSpecName"];
                    if (product["SecondSpecName"] != null)
                        productSpecialityItems += " " + product["SecondSpecName"];
                    if (product["ThirdSpecName"] != null)
                        productSpecialityItems += " " + product["ThirdSpecName"];
                    if (product["FourthSpecName"] != null)
                        productSpecialityItems += " " + product["FourthSpecName"];
                    if (product["FifthSpecName"] != null)
                        productSpecialityItems += " " + product["FifthSpecName"];
                    productSpecialityItems = (jQuery.trim(productSpecialityItems).length == 0) ? "-" : productSpecialityItems;

                    var basketString = StringDivision(productSpecialityItems);
                    $("#productSpec").text(basketString.toString());
                    $("#productImage").attr("src", rndMainPath + "/media/ProductImg/medium/" + product["ProductMainImage"]);
                    $("#productName").text(product["ProductName"]);
                    $("#productQuantity").text(product["Quantity"]);
                    $("#productQuantityTotal").text(productCount);
                    $("#productPrice").text(GetMoney(product["GrandTotal"]));
                    $("#grandTotal").text(GetMoney(data["GetBasketResult"]["GrandTotalPrice"]));
                    $("#productCode").text(product["ProductCode"]);

                    $("#miniCount").text(" " + productCount.toString() + " ÜRÜN");
                    $("#miniTotal").text(GetMoney(data["GetBasketResult"]["GrandTotalPrice"]));

                    //Sepet Açılır.
                    EffectToObject($(".sepet_acik"));
                    smallBasketState = false;
                }
                else {
                    //Mini Sepet Kapatılır.
                    CloseSmallBasket();
                    $("#miniCount").text(" 0 ÜRÜN");
                    $("#miniTotal").text("-");
                    smallBasketState = false;
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {

            }
        });
    }
}

//Mini Sepet Kapatılır.
var closeSmallBasketState = false;
function CloseSmallBasket() {
    closeSmallBasketState = true;
    $(".sepet_acik").hide();
    $(".sepet_acik").oneTime(500, function () {
        closeSmallBasketState = false;
    });
}

//Küçük Sepetin Açılıp Açılmayacağı Sayfalar
function GetOpenSmallBasket() {
    if (currentPage == "Sepetim.aspx" || currentPage == "FaturaBilgisi.aspx" || currentPage == "TeslimatBilgisi.aspx" || currentPage == "KargoSecimi.aspx" || currentPage == "SiparisiOnayla.aspx") {
        return false;
    }
    return true;
}
//////////////////////////////////////////////////////////////////
///Süreli Mesaj Verme(v1)
function MessageEffect(msj) {
    $("#message").show();
    $("#message").html(msj);
    $("#message").oneTime(6000, function () {
        $("#message").fadeOut("slow");
    });
}
//////////////////////////////////////////////////////////////////
///Süreli Mesaj Verme(v2)
function MessageEffectToObject(obj, msj) {
    $(obj).show();
    $(obj).html(msj);
    $(obj).oneTime(6000, function () {
        $(obj).text("");
    });
}
//////////////////////////////////////////////////////////////////
///Süreli Mesaj Verme(v3)
function MessageEffectToObjectWithTime(obj, msj, time) {
    $(obj).show();
    $(obj).html(msj);
    $(obj).oneTime(time, function () {
        $(obj).text("");
    });
}
//////////////////////////////////////////////////////////////////
///Süreli Element Çıkarma
function EffectToObject(obj) {
    $(obj).slideDown("slow");
    $(obj).oneTime(4000, function () {
        $(obj).fadeOut("slow");
    });
}

var cartString = "";
//////////////////////////////////////////////////////////////////
///Küçük sepette özelliği uzun olanların dışa taşmaması için yapılan method
function StringDivision(str) {
    if (str.length > 11) {
        cartString += str.substring(0, 11) + "\n";
        StringDivision(str.substring(11, str.length));
    }
    else {
        cartString += str;
    }
    return cartString;
}

//////////////////////////////////////////////////////////////////
///Arama Fonksiyonu/////////////
//function SearchKeyPress(e) {
//    var code = (e.keyCode ? e.keyCode : e.which);
//    if (code == 13) {
//        if (jQuery.trim($('[search_field=true]').val()).length > 0) {
//            window.location = rndMainPath + "/UrunArama.aspx?searchText=" + escape($('input[search_field=true]').val());
//        }
//        return false;
//    }
//}
//function Search() {
//    if (jQuery.trim($('input[search_field=true]').val()).length > 0) {
//        window.location = rndMainPath + "/UrunArama.aspx?searchText=" + escape($('input[search_field=true]').val());
//    }
//}

//////////////////////////////////////////////////////////////////
///Ebulten Enter tuşuna basınca
function NewsLetterKeyPress(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
        if (jQuery.trim($("input[email=true]").val()).length > 0) {
            AddNewsLetterMember();
        }
        return false;
    }
}
//////////////////////////////////////////////////////////////////
///Ebulten Fonksiyonu
function validate(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var address = email;
    if (reg.test(address) == false) {
        return false;
    }
    else
        return true;
}
//////////////////////////////////////////////////////////////////
///Haber Bülteni Wcf Gönderim
function AddNewsLetterMember() {

    var email = $("input[email=true]");

    if (validate(email.val()) == false) {
        EffectToObject($("span[revEmail=true]"));
        return false;
    }
    else
        $("span[revEmail=true]").hide();

    $(".loading").show();

    $("span[newlettermessage=true]").show();
    $.ajax({
        url: rndJqueryServiceName + "AddNewsLetterMember",
        type: "POST",
        contentType: "application/json",
        data: '{"email":"' + email.val() + '"}',
        dataType: "json",
        complete: function () {
            $(".loading").hide();
        },
        success: function (data) {

            $("span[newlettermessage=true]").hide();

            if (data["AddNewsLetterMemberResult"] == 0) {
                //Kaydedilemezse
            } else if (data["AddNewsLetterMemberResult"] == 1) {
                EffectToObject($("span[succecss=true]"));
                email.val("");
            }
            else if (data["AddNewsLetterMemberResult"] == 2) {
                EffectToObject($("span[beforeRecord=true]"));
                email.val("");
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (xhr.status == "500")
                $('#one').jGrowl($(".JsCodeErrorMessage").text());
            else
                $('#one').jGrowl($(".JsConnectionErrorMessage").text());
        }
    });
    return false;
}
///////////////////////////////////////////////////
//Türkçe Karakter Düzenlenmesi
function TurskishCharsetClear(word) {
    word = word.replace(/ /g, "-");
    word = word.replace(" ", "-");
    word = word.replace("ü", "u");
    word = word.replace("Ü", "u");
    word = word.replace("ğ", "g");
    word = word.replace("Ğ", "g");
    word = word.replace("İ", "i");
    word = word.replace("ı", "i");
    word = word.replace("ş", "s");
    word = word.replace("Ş", "s");
    word = word.replace("ç", "c");
    word = word.replace("Ç", "c");
    word = word.replace("ö", "o");
    word = word.replace("Ö", "o");
    word = word.replace("?", "");
    word = word.replace("#", "");
    word = word.replace("(", "");
    word = word.replace(")", "");
    word = word.replace("{", "");
    word = word.replace("}", "i");
    word = word.replace("[", "i");
    word = word.replace("]", "i");
    word = word.replace("+", "");
    word = word.replace("%", "");
    word = word.replace("--", "-");
    word = word.replace("---", "-");
    word = word.replace("----", "-");
    word = word.replace("---", "-");
    word = word.replace("--", "-");
    word = word.replace("%0A", "");
    word = word.replace("\n", "");
    word = word.replace("/", "");
    return word;
}
//////////////////////////////////////////////////////////////////
///Cookie Yönetim
var cookieList = function (cookieName) {
    var cookie = $.cookie(cookieName);
    var items = cookie ? cookie.split(/,/) : new Array();
    return {
        "add": function (val) {
            //Add to the items.
            items.push(val);
            //Save the items to a cookie.
            $.cookie(cookieName, items);
        },
        "clear": function () {
            //clear the cookie.
            $.cookie(cookieName, null);
        },
        "items": function () {
            //Get all the items.
            return items;
        }
    }
}

function getUrlVars(variableName) {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return unescape(vars[variableName]);
}

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}

//amount = price["Amount"].toString().replace(".", ",");
//    amount = (amount.split(",").length == 1) ? amount + ",00" : amount;
//    re = amount.split(",");
//    if (re[1].length == 1) {
//        amount = re[0].toString() + "," + re[1].toString() + "0";
//    }
//    return amount + " " + price["Unit"];

function GetMoney(price) {
    amount = price["Amount"].toString().replace(".", ",");
    amount = (amount.split(",").length == 1) ? amount + ",00" : amount;
    re = amount.split(",");
    if (re[1].toString().length == 1) {
        var integer = re[0].toString();
        if (integer.length > 3) {
            most = integer.substring(0, integer.length - 3);
            least = integer.substring(integer.length - 3, integer.length);
            amount = most + "." + least + "," + re[1].toString() + "0";
        }
        else {
            amount = re[0].toString() + "," + re[1].toString() + "0";
        }
    }
    else {
        var integer = re[0].toString();
        if (integer.length > 3) {
            most = integer.substring(0, integer.length - 3);
            least = integer.substring(integer.length - 3, integer.length);
            amount = most + "." + least + "," + re[1].toString();
        }
    }
    return amount + " " + price["Unit"];
}

function ConvertToMoney(price) {
    moneyText = price.split(",");
    if (moneyText.length == 1)
        return price + ",00 TL";
    else if (moneyText[1].length == 1)
        return moneyText[0] + "," + moneyText[1] + "0 TL";
    else if (moneyText[1].length == 2)
        return moneyText[0] + "," + moneyText[1] + " TL";
}



function DetailPopupState(value, link) {
    try {
        var islink = $(link).attr("islink");
        if (islink == undefined || islink == "False") {
            if (value) {
                $(".topicModalPopup").show();
                $("#loadedDiv").load(rndMainPath + "media/html_detail/" + $(link).attr("name"), function () {
                    $("#loading").fadeOut();
                    $("#loadedDiv").fadeIn();
                });
            }
            else {
                Boxy.get(".topicModalPopup").hide();
                $("#loading").fadeIn();
                $("#loadedDiv").fadeOut();
            }
        }
        else {
            window.location = $(link).attr(rndMainPath + "media/html_detail/" + $(link).attr("name"));
        }
    }
    catch (err) { alert(err); }
}

function newTopicModal() {
    new Boxy($(".topicModalPopup"), {
        modal: true, behaviours: function (c) {
            c.find('a:first').click(function () {
                newTopicModal();
            });
        }
    });
};


//////////////////////////////////////////////////////////////////
///                          Uyarılar
// Sistemde Varolan Yerel Değişkenlerdir,Başka Js dosyalarında kullanılmamalıdır!
// var rndJqueryServiceName;
// var rndMainPath;
// var currentPage;
// var smallBasketState = false;
// var cookieList
// var list; var thisIdIndex;
// var tSearch;
// var tEmail;
// var tDiscountCoupon;
///////////////////////////////////////////////////////////////

