var boxWidth = 335;
var space = 5;
var ItemLeftPos = 0;
var bModel = "";
var app = navigator.appName;
var ver = navigator.appVersion.split(".");
var effect = 400;
function sortLocations() {
    var j = 0;
    var pHeight = 0;
    var mHeight = 0;
    var nHeight = 0;
    var t = 0;
    var q = 0;
    var left, top, element, id;
    var arr = new Array(0, 0, 0);
    $(".alphaItem").each(function () {
        id = parseInt($(this).attr("id"));

        if (id > 3) {
            pHeight = $("#" + (id - 3)).height();
            nHeight = $("#" + (id - 3)).position().top;
        }

        switch (j % 3) {
            case 0:
                arr[0] += parseInt($(this).height());
                break;
            case 1:
                arr[1] += parseInt($(this).height());
                break;
            case 2:
                arr[2] += parseInt($(this).height());
                break;
        }

        //(j==0)?mHeight+=parseInt($(this).height()):"";
        $(this).animate({ left: ((boxWidth * j)), top: (pHeight + space + nHeight) + (q < 3 ? -145 : 0) }, 0);

        (j == 2) ? j = -1 : "";
        j++;
        q++;

    });

    $(".alphaItem[type='0']").hide();

    $(".alphaItem[type='0']").each(function () {
        $(this).fadeIn(t * effect)
        t++;
        $(this).removeAttr("type")
    });
    for (n = 0; n < 3; n++) {
        if (mHeight < arr[n]) { mHeight = arr[n]; }
    }

    $("#mainSection").css("position", "relative").css("left", "0px").height(mHeight > $(window).height() ? mHeight + 90 : $(window).height() - 280);

    (app == "Microsoft Internet Explorer" && ver[0] < 5) ? "" : fontSet();

    colorChanger();
    pictEffect();
}
var showingHeight = 0;
var actionFile = "";
function showInfo(id) {
    $(".contentNav").html("<div class='loader'></div>");
    $(".contentArea").html("<div class='loader'></div>");
    showingHeight = $("#" + id).height();
    if ($("#" + id).offset().top < $(window).scrollTop()) {
        $('html, body').animate({ scrollTop: ($(window).scrollTop() - ($(window).scrollTop() - $("#" + id).offset().top) - 18) }, 400);
    }
    else if (($("#" + id).offset().top + showingHeight + 20 + ($("#" + id).attr("classtype") == "style4" ? 200 : 0)) > ($(window).scrollTop() + $(window).height())) {
        $('html, body').animate({ scrollTop: ($(window).scrollTop() + (($("#" + id).offset().top + ($("#" + id).attr("model") == 1 ? ($("#" + id).attr("classtype") == "style4" ? 420 : 270) : showingHeight + ($("#" + id).attr("classtype") == "style4" ? 200 : 0))) - ($(window).scrollTop() + $(window).height())) + 18) }, 400);
    }

    $("#" + id).css("z-index", "3").attr("active", "0").removeClass("boxItem");
    $("#fx_mask").fadeIn(300);
    $("#fx_fake").height($("#fx_mask").height()).fadeIn(300);

    id % 3 == 0 ? ItemLeftPos = ($("#" + id).offset().left) - $("#" + id).width() : ItemLeftPos = ($("#" + id).offset().left - 10);
    $(".contentNav").removeAttr("style");
    $(".contentNav").attr("classType", $("#" + id).attr("classType"));
    $(".contentArea").attr("classType", $("#" + id).attr("classType"));
    if ($("#" + id).attr("classtype") == "style4") {
        $(".contentArea").height(showingHeight + 320);
    }
    else {
        $(".contentArea").height($("#" + id).attr("model") == "1" ? 270 : showingHeight);
    }

    if ($("#" + id).attr("model") == 0) {
        $(".contentNav").height(170).html("<a href='javascript:;' class='prev'></a><a href='javascript:;' class='next'></a><a href='javascript:;' class='close'></a>");
        $("#" + id + " p").clone().appendTo($(".contentNav"));
        closeItem();
    }
    else {
        $(".contentNav").html($("#" + id + " .defContent").html());
        $(".closeBtn").show();
    }

    if ($("#" + id).attr("model") == 1 && id % 3 != 0) {
        bModel = "left";
    }
    else if (id % 3 == 0 && $("#" + id).attr("model") == 1) {
        bModel = "right";
    }
    else if (id % 3 == 0) {
        bModel = "left";
    }
    else {
        bModel = "right";
    }
    $("#ItemContent").attr("boxStyle", bModel).animate({ left: ItemLeftPos, top: ($("#" + id).offset().top) + (-10) }, 0).fadeIn(0);
    
    $("#" + id).attr("model") == 1 ? actionFile = "getContents.aspx" : actionFile = "getProjects.aspx";

    $.ajax({
        type: 'GET',
        url: actionFile,
        data: "ID=" + $("#" + id).attr("dataid"),
        success: function (results) {
            $(".contentArea").html("<ul " + ($("#" + id).attr("classtype") == "style4" ? "style='height:100%'" : "") + " class=" + ($("#" + id).attr("model") == 0 ? "projectImages" : "contentTexts") + ">" + results + "</ul>");
            $("#" + id).attr("model") == 0 ? getImages() : getTexts();
            $("#" + id).attr("model") == 1 && $("#" + id).attr("classtype") != "style4" ? activeScroll() : "";
            (app == "Microsoft Internet Explorer" && ver[0] < 5) ? "" : fontSetx();
            if ($("#" + id).attr("classtype") == "style4") {
                memorize();
                $(".sender").click(function () {
                    if (!formControl()) {
                        return false;
                    }
                });
            }
        }

    });
    
}

function fx_mailControl(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function clearErrors() {
    $(".form input[type='text']").each(function () {
        if ($(this).attr("error")) {
            $(this).removeAttr("error");
        }
    })
    $(".form textarea").each(function () {
        if ($(this).attr("error")) {
            $(this).removeAttr("error");
        }
    })
}

function formControl() {
    if ($("input[name='nameSurname']").val() == "Ad Soyad") {
        clearErrors();
        $("input[name='nameSurname']").attr("error", "true");
        $("input[name='nameSurname']").focus();
        return false;
    }
    else if ($("input[name='phone']").val() == "Cep Telefonu") {
        clearErrors();
        $("input[name='phone']").attr("error", "true");
        $("input[name='phone']").mask("(999) 999 99 99");
        $("input[name='phone']").focus();
        return false;
    }
    else if ($("input[name='phone']").val() == "") {
        clearErrors();
        $("input[name='phone']").attr("error", "true");
        $("input[name='phone']").focus();
        return false;
    }
    else if ($("input[name='mail']").val() == "E-Posta") {
        clearErrors();
        $("input[name='mail']").attr("error", "true");
        $("input[name='mail']").focus();
        return false;
    }
    else if (!fx_mailControl($("input[name='mail']").val())) {
        clearErrors();
        $("input[name='mail']").attr("error", "true");
        alert("Geçerli bir mail adresi giriniz !");
        $("input[name='mail']").focus();
        return false;
    }
    else if ($("input[name='companyName']").val() == "Şirket Adı") {
        clearErrors();
        $("input[name='companyName']").attr("error", "true");
        $("input[name='companyName']").focus();
        return false;
    }
    else if ($("textarea[name='message']").val() == "Mesaj") {
        clearErrors();
        $("textarea[name='message']").attr("error", "true");
        $("textarea[name='message']").focus();
        return false;
    }
    else {
        $.ajax({
            type: 'GET',
            url: 'formSend.aspx',
            data: "ad=" + $("input[name='nameSurname']").val() + "&telefon=" + $("input[name='nameSurname']").val() + "&mail=" + $("input[name='nameSurname']").val() + "&sirketAdi=" + $("input[name='nameSurname']").val() + "&mesaj=" + $("input[name='nameSurname']").val() + "",
            success: function (result) {
                alert(result);
                $("textarea[name='message']").val("Mesaj");
                $("input[name='companyName']").val("Şirket Adı");
                $("input[name='mail']").val("E-Posta");
                $("input[name='phone']").val("Cep Telefonu");
                $("input[name='nameSurname']").val("Ad Soyad");
                clearErrors();
            }
        });
    }
}

function memorize() {
    $("input[name='nameSurname']").click(function () {
        if ($(this).val() == "Ad Soyad")
            $(this).val("");
    }).blur(function () {
        if ($(this).val() == "")
            $(this).val("Ad Soyad");
    });

    $("input[name='phone']").click(function () {
        if ($(this).val() == "Cep Telefonu")
            $(this).val("");
    }).blur(function () {
        if ($(this).val() == "")
            $(this).val("Cep Telefonu");
    });

    $("input[name='mail']").click(function () {
        if ($(this).val() == "E-Posta")
            $(this).val("");
    }).blur(function () {
        if ($(this).val() == "")
            $(this).val("E-Posta");
    });

    $("input[name='companyName']").click(function () {
        if ($(this).val() == "Şirket Adı")
            $(this).val("");
    }).blur(function () {
        if ($(this).val() == "")
            $(this).val("Şirket Adı");
    });

    $("textarea[name='message']").click(function () {
        if ($(this).val() == "Mesaj")
            $(this).val("");
    }).blur(function () {
        if ($(this).val() == "")
            $(this).val("Mesaj");
    });

}

var ImageCount = 0;
function getImages() {
    $("ul.projectImages li img").load(function () {
        $(this).show();
    })
    sortImage();
    currentImage = 0;
    $("ul.projectImages li:eq(0)").attr("active", "1").show();
    ImageCount = $("ul.projectImages li").length;
    $("a.prev").addClass("passive");
    $("a.prev").click(function () {
        if ($("ul.projectImages li[active='1']").attr("tabindex") > 0) {
            $("a.next").removeClass("passive");
            currentImage = $("ul.projectImages li[active='1']").attr("tabindex");
            $("ul.projectImages li").removeAttr("active").animate({ left: '+=333' }, 200)
            $("ul.projectImages li[tabindex='" + (currentImage - 1) + "']").attr("active", "1");
        }

        if ($("ul.projectImages li[active='1']").attr("tabindex") == 0) {
            $("a.prev").addClass("passive");
        }
    })
    $("a.next").click(function () {
        if (($("ul.projectImages li[active='1']").attr("tabindex") + 1) < ImageCount) {
            $("a.prev").removeClass("passive");
            currentImage = $("ul.projectImages li[active='1']").attr("tabindex");
            $("ul.projectImages li").removeAttr("active").animate({ left: '-=333' }, 200)
            $("ul.projectImages li[tabindex='" + (currentImage + 1) + "']").attr("active", "1");
        }

        if (($("ul.projectImages li[active='1']").attr("tabindex") + 1) == ImageCount) {
            $("a.next").addClass("passive");
        }
    })
}

function getTexts() {

}

function sortImage() {
    $("ul.projectImages li").each(function (i) {
        $(this).attr("tabindex", i).css("left", (i * 333) + "px")
    })
}

function closeItem() {
    $("a.close").click(function () {
        $("div[active='0']").children(".defContent").css("display", "table-cell");
        $("div[active='0']").removeAttr("active").css("z-index", "1").addClass("boxItem");
        $("#fx_mask").fadeOut();
        $("#ItemContent").fadeOut();
        $(".closeBtn").fadeOut();
    })
}

var totHeight = 0;
function activeScroll() {
    $("div.contentArea ul.contentTexts li").each(function () {
        $(this).height($(this).height() - ((app == "Microsoft Internet Explorer" && ver[0] < 5) || app != "Microsoft Internet Explorer" ? 20 : 52));
        totHeight += $(this).height();
    });
    if (totHeight > 280) { $('.contentTexts').jScrollPane(); }
    totHeight = 0;
}


function fontSet() {
    Cufon.replace('span,div', { fontFamily: 'mocha-font'});
}

function fontSetx() {
    Cufon.replace('#ItemContent *', { fontFamily: 'mocha-font' });
}

function colorChanger() {
    //$(".defContent").hover(function () { fontSet(); })
}

function pictEffect() {
    $("div.fade_over").mouseover(function () {
        $(this).stop().animate({ opacity: 0 }, 400)
    }).mouseout(function () {
        $(this).stop().animate({ opacity: 1 }, 300)
    });
}

var elements = new Array(100, 150, 300, 400, 600, 700);

$(window).resize(function () {
    $("#footer").css("left", (($(window).width() - ((boxWidth * 3) + 22) + (space * 2))) / 2 + "px");
});

$(function () {

    $(".closeBtn").click(function () {
        $("div[active='0']").children(".defContent").css("display", "table-cell");
        $("div[active='0']").removeAttr("active").css("z-index", "1").addClass("boxItem");
        $("#fx_mask").fadeOut();
        $("#ItemContent").fadeOut();
        $(".closeBtn").fadeOut();
    })

    $("#footer").css("left", (($(window).width() - ((boxWidth * 3) + 22) + (space * 2))) / 2 + "px");

    (app == "Microsoft Internet Explorer" && ver[0] < 5) ? "" : fontSet();

    $("#fx_mask").click(function () {
        $("div[active='0']").children(".defContent").css("display", "table-cell");
        $("div[active='0']").removeAttr("active").css("z-index", "1").addClass("boxItem");
        $(this).fadeOut();
        $("#ItemContent").fadeOut(300);
        $(".closeBtn").fadeOut();
    })

    var itemHeight = 0;
    var currentItem = 0;
    var lastItem = 0;
    var showing = 0;
    var elem = "";
    $.ajax({
        url: 'Database.aspx',
        dataType: 'json',
        success: function (JSON) {
            $.each(JSON.References, function (i, reference) {
                if ($(window).height() > itemHeight) {
                    elem += "<div id='" + (i + 1) + "' dataid='" + reference.id + "' type='0' model='" + (reference.model == 0 || reference.model == 1 ? "1" : "0") + "' classType='style" + reference.style + "' onclick='showInfo(" + (i + 1) + ");' class='alphaItem boxItem style" + reference.style + " box" + reference.model + "'><div class='opaque'></div>";
                    elem += "<div class='defContent'>";
                    if (reference.image != undefined) { elem += "<div class='fade' style='height:" + elements[reference.model] + "px;'><img src='" + reference.image + "' /></div><div class='fade_over' style='height:" + elements[reference.model] + "px;'></div><p><em>" + reference.name + "</em><em>" + reference.info + "</em><a href='" + reference.address + "' target='_blank' class='address' title='" + reference.address + "'>" + reference.address + "</a></p>"; } else { elem += "<span>" + reference.name + "</span><em>" + reference.adder + "</em>"; }
                    elem += "</div></div>";
                    (i % 3 == 0) ? itemHeight += elements[reference.model] : "";
                    currentItem = i;
                }
                else {
                    showing = currentItem + 1;
                    if (showing % 3 != 0) {
                        elem += "<div id='" + (i + 1) + "' dataid='" + reference.id + "' type='0' model='" + (reference.model == 0 || reference.model == 1 ? "1" : "0") + "' classType='style" + reference.style + "' onclick='showInfo(" + (i + 1) + ");' class='alphaItem boxItem style" + reference.style + " box" + reference.model + "'><div class='opaque'></div>";
                        elem += "<div class='defContent'>";
                        if (reference.image != undefined) { elem += "<div class='fade' style='height:" + elements[reference.model] + "px;'><img src='" + reference.image + "' /></div><div class='fade_over' style='height:" + elements[reference.model] + "px;'></div><p><em>" + reference.name + "</em><em>" + reference.info + "</em><a href='" + reference.address + "' target='_blank' class='address' title='" + reference.address + "'>" + reference.address + "</a></p>"; } else { elem += "<span>" + reference.name + "</span>" + (reference.adder != "" ? "<em>" + reference.adder + "</em>" : ""); }
                        elem += "</div></div>";
                        (i % 3 == 0) ? itemHeight += elements[reference.model] : "";
                        currentItem = i;
                    }
                }
                $('#mainSection .outline').append(elem);
                elem = "";
                lastItem = i;
            });
            sortLocations();
            scrolling(currentItem, lastItem);
            loadImages();
        }
    });

})

function scrolling(value, total) {
    effect = 800;
    var count = 0;
    var elem = "";
    $(window).scroll(function () {
        $("#footer").hide();
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            $.ajax({
                url: 'Database.aspx',
                dataType: 'json',
                success: function (JSON) {
                    $.each(JSON.References, function (i, reference) {
                        if (i > value && count < 3 && i <= total) {
                            elem += "<div id='" + (i + 1) + "' dataid='" + reference.id + "' type='0' model='" + (reference.model == 0 || reference.model == 1 ? "1" : "0") + "' classType='style" + reference.style + "' onclick='showInfo(" + (i + 1) + ");' class='alphaItem boxItem style" + reference.style + " box" + reference.model + "'><div class='opaque'></div>";
                            elem += "<div class='defContent'>";
                            if (reference.image != undefined) { elem += "<div class='fade' style='height:" + elements[reference.model] + "px;'><img src='" + reference.image + "' /></div><div class='fade_over' style=' height:" + elements[reference.model] + "px;'></div><p><em>" + reference.name + "</em><em>" + reference.info + "</em><a href='" + reference.address + "' target='_blank' class='address' title='" + reference.address + "'>" + reference.address + "</a></p>"; } else { elem += "<span>" + reference.name + "</span>" + (reference.adder != "" ? "<em>" + reference.adder + "</em>" : ""); }
                            elem += "</div></div>";
                            count++;
                        }
                    });

                    $('#mainSection  .outline').append(elem);
                    elem = "";
                    value += count;
                    count = 0;
                    sortLocations();
                    loadImages();
                }
            });
        };
        $("#footer").show();
    })
}

function loadImages() {
    $(".fade img").load(function () {
        $(this).parent("div").css("background","url("+$(this).attr("src")+") left top no-repeat");
        $(this).parent("div").next().css("background", "url(" + $(this).attr("src") + ") -330px top no-repeat");
    })
}
