﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
/// <reference path="jquery.form.js" />
/// <reference path="jquery.Jcrop.js" />
/// <reference path="jquery-ui-1.8.6.custom.min.js" />

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-9698309-6']);
_gaq.push(['_trackPageview']);

(function () {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
        "use strict";

        if (this === void 0 || this === null)
            throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0)
            return -1;

        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) // shortcut for verifying if it's NaN
                n = 0;
            else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }

        if (n >= len)
            return -1;

        var k = n >= 0
		  ? n
		  : Math.max(len - Math.abs(n), 0);

        for (; k < len; k++) {
            if (k in t && t[k] === searchElement)
                return k;
        }
        return -1;
    };
}

var newPopup = function (url) {
    popupWindow = window.open(
		url, 'popUpWindow', 'height=300,width=600,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}

var limitText = function (limitNum) {
    var limitField = document.getElementById("mass");
    var limitCount = document.getElementById("txtLimitCount");
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
}

String.prototype.Encode = function () {
    if (this === null) throw new TypeError();
    return this.replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
}

var contact = function () { };

var newImageName = "";

var site = {
    params: {
        id: 0,
        age: "''",
        date: "''",
        address: "''",
        address2: "''",
        address3: "''",
        person: "''",
        x: 0,
        y: 0,
        w: 0,
        h: 0,
        lid: 0,
        mid: 0,
        style: "''",
        author: "''",
        mass: "''",
        mass1: "''",
        mass2: "''",
        fn: "''"
    },
    front: { x: 0, y: 0, w: 0, h: 0, ratio: 1, person: "''", fn: "''" },
    inside: { x: 0, y: 0, w: 0, h: 0, ratio: 1, person: "''", fn: "''", mid: "''" },
    doc1id: "",
    doc2id: ""
};

$(document).ready(function () {

    if ($("#send").is("input")) {

        $("#send").click(function (event) {
            var result = false;

            $(this).addClass("hideButton");
            $("#note").text("Your message is sending....");

            var e = $("#Email");
            var m = $("#Message");
            if (e.val() == "") {
                e.addClass("alert");
                e.focus();
            }
            else if (m.val() == "") {
                e.removeClass("alert");
                m.addClass("alert");
                m.focus();
            }
            else {
                result = true;
            };
            return result;
        });

        contact = function (data) {
            var e = $("#Email");
            $("#note").text(data.answer ? "Your email has been sent!" : "Incorrect email.");
        };
    }
    $('#tab-1').hide();
    $('#tab-2').hide();
    $('#tab-3').hide();
    $('#last').hide();

    $('#tabs div:first').show();
    $('#tabs ul li:first').addClass('active');
    $('#tabs ul li a').click(function () {
        $('#tabs ul li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('#tab-1').hide();
        $('#tab-2').hide();
        $('#tab-3').hide();
        $('#last').hide();
        $(currentTab).show();
        if (currentTab == "#last") {
            doc1preview();
            doc2preview();
        }
        return false;
    });



    $("#go-tab-2,#back-tab-2").click(function () { $("#tabs ul li a[href='#tab-2']").click(); });
    $("#back-tab-1").click(function () { $("#tabs ul li a[href='#tab-1']").click(); });
    $("#go-tab-last,#go-tab-4").click(function () { $("#tabs ul li a[href='#last']").click(); });
    $("#go-tab-3,#back-tab-3").click(function () { $("#tabs ul li a[href='#tab-3']").click(); });

    $('#doc1id>li>img').click(function () {
        site.front.w = 0;
        site.doc1id = $(this).attr("data-id");
        site.front.ratio = $(this).attr("data-ar");

        var copyName = "";

        if ($("#container.memoriam").is("div")) {
            var n = $(this).attr("data-name").split("_"); //DS_matchoutside_07-300
            site.inside.mid = (n[1] == "matchoutside") ? "'DS_match_Inside_" + n[2] + "'" : "''"; //we have match in the name only for new templates? yes - the this correct need assign this only if front name is "dw_match_outide_? right? yes"  but i think better use ids - just read on server side this ids and add to img tag as we do with data-name..let test this before
        }

        if ($("#container.memoriamWallet").is("div")) {
            var n = $(this).attr("data-name").split("_"); //ds_walletoutside_1
            copyName = (n[1] == "walletoutside") ? "ds_walletinside_" + n[2] + "" : "";

            $('#doc2id>li>img').each(function () {

                if ($(this).attr("data-name") == copyName) {
                    site.doc2id = $(this).attr("data-id");
                    $('#backPreview').attr("src", $(this).attr("src"));
                    site.inside.w = 0;
                    site.inside.ratio = $(this).attr("data-ar");
                }

            });

        }

        $('#docpreview').attr("src", $(this).attr("src"));
        if (($(this).attr("data-wt") || "").toLowerCase() == "true") {
            $("#userinput").show();
            $("#preview").show();
        }
        else {
            $("#userinput").hide();
            $("#preview").hide();
        }
        var toshow = $(this).attr("data-fields");
        $(".person,.photo").hide(); //hide all inputs that may be opened before
        $(toshow).show();
    })
	.first().click();

    if ($("#container.memoriam").is("div")) {
        $('#doc2id>li>img').click(function () {
            site.doc2id = $(this).attr("data-id");
            $('#backPreview').attr("src", $(this).attr("src"));
            site.inside.w = 0;
            site.inside.ratio = $(this).attr("data-ar");

            var g = $("#gender").val();
            var pn = $(this).parent().attr("data-name").split("_");
            $("#verse").empty();
            $("#doc2id>li").filter(function (i) {
                var n = $(this).attr("data-name").split("_");
                var ng = n[4]; //gender in "ds_inside_border2_verse4_f"
                var result = (ng == "u" || ng == g) && pn[2] == n[2];
                return result;
            }).children("img").clone()
			.click(function () {
			    site.doc2id = $(this).attr("data-id");
			    $('#backPreview').attr("src", $(this).attr("src"));
			    site.inside.ratio = $(this).attr("data-ar");
			    site.inside.w = 0;
			})
			.each(function () {
			    $(this).appendTo($('<li class="versePreview"></li>').appendTo($("#verse")));
			    $(this).removeClass("borderPhoto");
			});
        });

        var rebuildTab2 = function () {
            $("#doc2id>li:hidden").show();
            var g = $("#gender").val();
            var borders = [];
            $("#doc2id>li").filter(function (i) {
                var n = $(this).attr("data-name").split("_");
                var ng = n[4]; //gender in "ds_inside_border2_verse4_f"
                var result = !(ng == "u" || ng == g);
                if (!result) {
                    var b = n[2]; //border in "ds_inside_border2_verse4_f"
                    if ($.inArray(b, borders) == -1) {
                        borders.push(b);
                    }
                    else {
                        result = true;
                    }
                }
                return result;
            }).hide();
            $("#doc2id>li>img").first(":visible").click();
        };

        $("#gender").change(function () {
            rebuildTab2();
        }).change(); //select gendered templates
    }
    else if ($("#container.memoriamWallet").is("div")) {
    }
    else {
        $('#doc2id>li>img').click(function () {
            site.doc2id = $(this).attr("data-id");
            $('#backPreview').attr("src", $(this).attr("src"));
            site.inside.ratio = $(this).attr("data-ar");
            site.inside.w = 0;
        })
		.first().click();
    }
    $('#lid>li>img').click(function () {
        site.params.lid = $(this).attr("data-id");

        $('#linside').attr("src", $(this).attr("src")).removeClass("prev2");
        if ($("#container.memoriam").is("div")) {
            if ($(this).attr("data-name") == "ds_inside.right.blank.pdf") {
                $("#userinput").show();
                $('#linside').attr("src", $(this).attr("data-origSrc")).removeClass("prev2");
                $(this).attr("src", "/Content/blankImage.jpg");
            } else {
                $("#userinput").hide();
                $("#mass").val("");
                $("#previewC").click();
            }
        }
    })
	.slice(0, 2).click();

    var re = /'/i;
    var doc1preview = function () {
        if (site.doc1id != "") {
            $('#loadingGif').show();
            $('#loadingGif3').show();
            $('#loadingGifFinal').show();
            site.params.mid = "''"; //always reset it so we never send mid for front
            site.params.id = site.doc1id;
            site.params.person = "'" + ($("#person").val() || "").Encode() + "'";
            site.params.date = "'" + ($("#date").val() || "").Encode() + "'";
            if (site.front.w != 0) {
                site.params.fn = "'" + site.front.fn + "'";
                site.params.x = site.front.x;
                site.params.y = site.front.y;
                site.params.w = site.front.w;
                site.params.h = site.front.h;
            }
            else {
                site.params.fn = "''";
                site.params.x = 0;
                site.params.y = 0;
                site.params.w = 0;
                site.params.h = 0;
            }
            //here we reading person for front - let use the same id for all fronts so no needs to read from "different" inputs, if you need to use person as id - let use, just rename in the code 
            $.getJSON("/ajax.svc/Preview?" + $.param(site.params), function (data) {
                $("#docpreview").attr("src", data.d.Preview);
                $("#doc1").attr("src", data.d.Preview);
                $('#loadingGif').hide();
                $('#loadingGif3').hide();
                $('#loadingGifFinal').hide();
            });
        }
    };
    $('#preview').click(doc1preview);

    var doc2preview = function () {//TODO: make user input universal -to use same age, person inputs
        if (site.doc2id != "") {
            $('#loadingGif2').show();
            $('#loadingGifFinal2').show();
            if ($("#container.memoriam").is("div") | $("#container.memoriamWallet").is("div")) {
                $('#loadingGif').show();
            }
            site.params.id = site.doc2id;
            site.params.mid = site.inside.mid;
            site.params.age = "'" + ($("#age").val() || "").Encode() + "'";
            site.params.person = "'" + ($("#personB").val() || "").Encode() + "'";
            site.params.date = "'" + ($("#dateB").val() || "").Encode() + "'";
            site.params.address = "'" + ($("#address").val() || "").Encode() + "'";
            site.params.address2 = "'" + ($("#address2").val() || "").Encode() + "'";
            site.params.address3 = "'" + ($("#address3").val() || "").Encode() + "'";
            var authorValue = "";
            if ($("#authorCustom").val() == "") {
                authorValue = $("#author").val()
            } else {
                authorValue = $("#authorCustom").val()
            }
            site.params.author = "'" + (authorValue || "").Encode() + "'";
            site.params.style = "'" + ($("input:checked[name='style']").val() || $("#style").val() || "") + "'";
            site.params.mass = "'" + ($("#mass").val() || "") + "'";
            if ($("#container.csacknowledgement").is("div")) {
                if ($("#massOptions").val() == "The Holy Sacrifice of the Mass will be offered for your intentions.") {
                    site.params.mass1 = "'" + ("The Holy Sacrifice of the Mass will be") + "'";
                    site.params.mass2 = "'" + ("offered for your intentions.") + "'";
                } else if ($("#massOptions").val() == "The Holy Sacrifice of the Mass has been offered for your intentions.") {
                    site.params.mass1 = "'" + ("The Holy Sacrifice of the Mass has been") + "'";
                    site.params.mass2 = "'" + ("offered for your intentions.") + "'";
                } else {
                    site.params.mass1 = "'" + "'";
                    site.params.mass2 = "'" + "'";
                }
            }
            if (site.inside.w != 0) {
                site.params.fn = "'" + site.inside.fn + "'";
                site.params.x = site.inside.x;
                site.params.y = site.inside.y;
                site.params.w = site.inside.w;
                site.params.h = site.inside.h;
            } else {
                site.params.fn = "''";
                site.params.x = 0;
                site.params.y = 0;
                site.params.w = 0;
                site.params.h = 0;
            }
            $.getJSON("/ajax.svc/Preview?" + $.param(site.params), function (data) {
                $("#backPreview").attr("src", data.d.Preview);
                $("#doc2").attr("src", data.d.Preview);
                if ($("#container.memoriam").is("div") | $("#container.memoriamWallet").is("div")) {
                    $('#loadingGif').show();
                    $("#linside").attr("src", data.d.Preview).addClass("prev2");

                }
                $('#loadingGif2').hide();
                $('#loadingGifFinal2').hide();
                if ($("#container.memoriam").is("div") | $("#container.memoriamWallet").is("div")) {
                    $('#loadingGif').hide();
                }
            });

        }
    };
    $('#previewB,#previewC').click(doc2preview);
    $('#previewA').click(doc1preview);

    var track = function (c) {
        site.inside.x = c.x;
        site.inside.y = c.y;
        site.inside.w = c.w;
        site.inside.h = c.h;
        //we have c.ratio right?no - rato we storing in the images - awhere we clicking then know ratio
    };

    site.jcropf = function (w, h) {
        site.jcrop = $.Jcrop('#photoPreview', {
            onSelect: track,
            onChange: track,
            trueSize: [w, h],
            bgColor: 'white',
            bgOpacity: .5,
            setSelect: [0, 0, 200, 200],
            aspectRatio: site.inside.ratio
        });
    };

    $("#cropper").ajaxForm({
        iframe: true,
        dataType: "json",
        beforeSubmit: function () {
            $('#picLoaderGif').show();
        },
        success: function (result) {
            site.jcrop && site.jcrop.destroy();
            $('#picLoaderGif').hide();
            var p = $('#photoPreview');
            p.attr("src", result.file);
            p.css("height", (p.width() * result.h / result.w) + "px");
            site.jcropf(result.w, result.h);
            site.inside.fn = result.file;
        },
        error: function (xhr, textStatus, errorThrown) {
        }
    });

    $("#f").change(function () { $("#cropper").submit(); });

    //cropper for front
    var track2 = function (c) {
        site.front.x = c.x;
        site.front.y = c.y;
        site.front.w = c.w;
        site.front.h = c.h;
    };

    site.jcropf2 = function (w, h) {
        site.jcrop2 = $.Jcrop('#photoPreview_front', {
            onSelect: track2,
            onChange: track2,
            trueSize: [w, h],
            bgColor: 'white',
            bgOpacity: .5,
            setSelect: [0, 0, 200, 200],
            aspectRatio: site.front.ratio//we need separate ratio too as each photo may have own
        });
    };

    $("#cropper_front").ajaxForm({
        iframe: true,
        dataType: "json",
        beforeSubmit: function () {
            $('#picLoaderGif_front').show();
        },
        success: function (result) {
            site.jcrop2 && site.jcrop2.destroy();
            $('#picLoaderGif_front').hide();
            var p = $('#photoPreview_front');
            p.attr("src", result.file);
            p.css("height", (p.width() * result.h / result.w) + "px");
            site.jcropf2(result.w, result.h);
            site.front.fn = result.file;
        },
        error: function (xhr, textStatus, errorThrown) {
        }
    });

    $("#f_front").change(function () { $("#cropper_front").submit(); });
    //end of cropper for front

    $("#btn_approve").click(function () {
        if ($("#container.csacknowledgement.single").is("div")) {
            $.getJSON("/ajax.svc/AddToCart?" + $.param({ doc1: site.doc2id, doc2: site.doc2id }), function (data) {
                $("#note").text(data.d.AddToCart).fadeIn();
                $("#linkToCart").fadeIn();
                $(".appButton").fadeOut();

            });
        }
        else {
            $.getJSON("/ajax.svc/AddToCart?" + $.param({ doc1: site.doc1id, doc2: site.doc2id }), function (data) {
                $("#note").text(data.d.AddToCart).fadeIn();
                $("#linkToCart").fadeIn();
                $(".appButton").fadeOut();
            });
        }
    }
	);

    if ($("#products").is("table")) {//this is part of cart... First thing is this should be div, i change from ul to div - to table
        site.kr = $("#products>tbody>tr[data-type='Keyrings']");
        site.m = $("#products>tbody>tr[data-type='Memoriam_Cards']");
        site.bk = $("#products>tbody>tr[data-type='Bookmarks']");
        site.ack = $("#products>tbody>tr[data-type='Acknowledgement_Cards']");
        var recalculate = function () {
            if ($("#products>tbody>tr[data-type]").is("tr")) {
                var total = 0;
                $(".price").each(function (i, e) { total += (($(this).val() || 0) - 0); })
                var to = $("#To option:selected").attr("data-price") || 10;
                total += (to - 0);
                $("#shipprice").html("&euro;" + to + ".00");
                $("#total").html("&euro;" + total + ".00"); //bad idea but to fix faster let just add .00
                $("#subtotal").html("&euro;" + (total - to - 0) + ".00");
            }
            else {
                $("#products").parent().remove();
                $("#note").text("You cart is empty").show();
            }
        };

        $("#To").change(function () { recalculate(); });

        site.price = {
            range: [25, 35, 50, 75, 100, 125, 150, 200, 250, 300, 400],
            Memoriam_Cards: { 25: 92, 35: 109, 50: 131, 75: 164, 100: 197, 125: 231, 150: 250, 200: 317, 250: 382, 300: 438, 400: 535, "+100": 99 },
            Bookmarks: { 25: 92, 35: 109, 50: 131, 75: 164, 100: 197, 125: 231, 150: 250, 200: 317, 250: 382, 300: 438, 400: 535, "+100": 99 },
            Acknowledgement_Cards: { 25: 37, 35: 44, 50: 52, 75: 64, 100: 73, 125: 82, 150: 90, 200: 99, 250: 109, 300: 119, 400: 137, "+100": 22 },
            Keyrings: { 1: 8, "+1": 5 }
        };

        $("#products>tbody>tr>td>.remove").click(function () {
            var p = $(this).parent().parent();
            $.getJSON("/ajax.svc/RemoveFromCart?" + $.param({ pdf1: p.attr("data-pdf1"), pdf2: p.attr("data-pdf2") }), function (data) {
                $("#note").text(data.d.RemoveFromCart).fadeIn(function () { p.hide(400, function () { p.remove(); recalculate(); }); });
            });
        });

        $("#products>tbody>tr>td>.minus,#products>tbody>tr>td>.plus").click(function () {
            var isplus = $(this).is(".plus");
            var p = $(this).parent();
            var c = p.children(".count");
            var t = p.parent().attr("data-type");
            var count = parseInt(c.val());
            var price = 0;
            if (t != "Keyrings") {
                var cur = site.price.range.indexOf(count);

                if (isplus) {
                    if (cur > -1 && cur < site.price.range.length - 2) {
                        cur++;
                        count = site.price.range[cur];
                    } else {
                        count += 100;
                    }
                }
                else {
                    if (cur > 0 && cur < site.price.range.length) {
                        cur--;
                        count = site.price.range[cur];
                    } else if (cur == -1) {
                        count -= 100;
                    }
                }
                var p400 = site.price[t][400];
                var pplus = site.price[t]["+100"];
                var price = count > 400 ? p400 + pplus * (Math.ceil((count - 400) / 100)) : site.price[t][count];
            }
            else {//keyrings
                if (isplus) {
                    count++;
                }
                else if (count > 1) {
                    count--;
                }
                price = 8 + 5 * (count - 1);
            }
            c.val(count);
            p.parent().children("td").children(".price").val(price);
            recalculate();
        });
    }
});
