﻿/// <reference path="../../../Admin/js/jquery-1.4.1-vsdoc.js" />

TakZarf = {
    Init: function () {
        this.Validation.Init();
        this.ContactUsForm.Init();
        this.CustomerFileUplaodForm.Init();
        this.PhotoAlbum.Init();
        this.LoginForm.Init();
        this.ProductsSearch.Init();
        this.VideoPlayer.Init();
        this.ThemeSwitcher.Init();
        this.ProductDetail.Init();
        this.Animations.AnimateLogo();
        this.Analytics.Init();
    },

    ThemeSwitcher: {
        Init: function () {
            if ($.cookie('TakzarfpplasticTheme') !== null) {
                if ($.cookie('TakzarfpplasticTheme') === "Gray") {
                    $("body").addClass('GrayTheme');
                }
            }

            $("#Header .ChangeThemeColor").click(function () {
                $("body").toggleClass("GrayTheme");
                if ($("body").hasClass("GrayTheme")) {
                    $.cookie('TakzarfpplasticTheme', 'Gray', { expires: 60, path: '/' });
                }
                else {
                    $.cookie('TakzarfpplasticTheme', 'Red', { expires: 60, path: '/' });
                }
                return false;
            });

        }
    },

    Animations: {
        AnimateLogo: function () {
            var LogoShine = $("#Header .Logo .Shine");
            LogoShine.stop().animate({
                opacity: 0.9
            }, 300, function () {
                LogoShine.animate({
                    opacity: 0.0
                }, 500);
                setTimeout("TakZarf.Animations.AnimateLogo()", 3000);
            });
        }
    },

    VideoPlayer: {
        Init: function () {
            $(".VideoBox a").colorbox();
        }
    },

    PhotoAlbum: {
        Init: function () {
            try {
                $(".SlidesContainer").before("<div class='pagination'>").cycle({
                    fx: 'scrollRight',
                    pager: '.pagination'
                });
            }
            catch (e) { }


            $(".PhotoGallery a").colorbox();
        }
    },

    LoginForm: {
        Init: function () {
            $("#TopBar .Button").click(function () {
                var Form = $("#LoginForm");
                var UserName = Form.find("input[name=Username]").val();
                var Pass = Form.find("input[name=Password]").val();
                if (UserName === "Username" && Pass === "Password") {

                    return false;
                }

                $.ajax({
                    url: "Admin/Plugins/Login/default.php?Function=LogIn",
                    type: "post",
                    dataType: "text",
                    data: $("#LoginForm").serialize(),
                    success: function (Result) {
                        if (Result.substring(0, 1) === "/") {
                            document.location.href = Result;
                        } else {
                            Form.find(".Text").hide().end()
                                .find(".Button").hide().end()
                                .find(".checkbox").hide().end()
                                .find(".checkboxText").hide().end()
                                .find(".ErrorText").text(Result);
                            setTimeout("TakZarf.ShowError();", 3000);
                        }
                    }
                });
                return false;
            });
        }
    },
    Logout: function (RootPath) {
        $.ajax({
            url: RootPath + 'Admin/Plugins/Logout/default.php',
            type: "get",
            dataType: "html",
            data: {
                Function: "LogOut"
            },
            success: function (RootPath) {
                window.location.href = RootPath;
            }
        });
    },
    ShowError: function () {
        var Form = $("#LoginForm");
        Form.find(".Text").show().end()
            .find(".Button").show().end()
            .find(".checkbox").show().end()
            .find(".checkboxText").show().end()
            .find(".ErrorText").text("");
    },
    Validation: {
        Init: function () {
            var Form = $("#LoginForm");
            $("#TopBar .Username").click(function () {
                if (Form.find(".Username").val() === "Username") {

                    Form.find("input[name='Username']").val("");
                    if (Form.find(".Password").val() === "") {
                        Form.find("input[name='Password']").val("Password");
                    }
                }
                return false;
            });

            $("#TopBar .Password").click(function () {
                if (Form.find(".Password").val() === "Password") {

                    Form.find("input[name='Password']").val("");
                    if (Form.find(".Username").val() === "") {
                        Form.find("input[name='Username']").val("Username");
                    }
                }
                return false;
            });

            $("#TopBar .Username, #TopBar .Password").blur(function () {

                if (Form.find(".Username").val() === "") {
                    Form.find("input[name='Username']").val("Username");
                }

                if (Form.find(".Password").val() === "") {
                    Form.find("input[name='Password']").val("Password");
                }

                return false;
            });

            this.LocalizeValidatorForPersian();

            $("form").each(function () {
                $(this).validate()
            });

        },
        LocalizeValidatorForPersian: function () {
            jQuery.extend(jQuery.validator.messages, {
                required: "*",
                email: "*"
            });
        }
    },

    ContactUsForm: {
        Init: function () {
            $("#ContactSection").change(function () {
                var FormNewActionAtrribute = $(this).children("option:selected").attr("action");
                $(this).closest("form").attr("action", FormNewActionAtrribute);
            });
        }
    },

    CustomerFileUplaodForm: {
        Init: function () {
            var Form = $("#CustomerFileForm");
            Form.submit(function () {
                if (Form.valid()) {
                    $("#CustomerFileForm").hide();
                    $("#CustomerFileUplaodProgressIndicator").fadeIn();
                    Form.ajaxSubmit({
                        type: "POST",
                        dataType: "json",
                        url: "CustomerFiles",
                        success: function (result, statusText, xhr, $form) {
                            window.location.reload()
                        }
                    });
                }
                return false;
            })
        }
    },

    ProductsSearch: {
        Literals: {
            Gram: 'گرم',
            Millimeters: 'میلی متر',
            Code: 'کد',
            DetailPageUrl: 'ProductDetail',
            ProductName: 'NameFa'
        },
        Init: function () {
            $("#Products .Options .Shapes a").click(function (Event) {
                CurrentShape = $(Event.target);
                CurrentShape.parent().addClass("Selected").siblings().removeClass("Selected");
                TakZarf.ProductsSearch.LoadCapacities();
                return false;
            });

            $("#Products .Options .Capacities select").change(function (Event) {
                TakZarf.ProductsSearch.LoadDiameters();
                return false;
            });

            $("#Products .Options .Diameters select").change(function (Event) {
                TakZarf.ProductsSearch.LoadProducts();
                return false;
            });

            TakZarf.ProductsSearch.LoadCapacities();
        },

        LoadCapacities: function () {
            var CapacitiesElement = $("#Products .Options .Capacities");
            CapacitiesElement.children(".Loading").show().end()
					.children("table").hide();

            var DiametersElement = $("#Products .Options .Diameters");
            DiametersElement.children(".Loading").show().end()
					.children("table").hide();

            $.ajax({
                url: 'Admin/Plugins/Products/default.php',
                type: "post",
                cache: false,
                dataType: "json",
                data: {
                    Function: "GetCapacityByShape",
                    Shape: $("#Products .Options .Shapes .Selected a").attr("value")
                },
                success: function (Capacities) {

                    var OptionsCode = '';
                    for (var i = 0; i < Capacities.length; i++) {
                        OptionsCode += "<option value='" + Capacities[i] + "'>" + Capacities[i] + " " + TakZarf.ProductsSearch.Literals.Gram + "</option>";
                    }
                    CapacitiesElement.find("select").html(OptionsCode).end()
							.children(".Loading").hide().end()
							.children("table").show();
                    TakZarf.ProductsSearch.LoadDiameters();
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        },

        LoadDiameters: function () {

            var DiametersElement = $("#Products .Options .Diameters");

            DiametersElement.children(".Loading").show().end()
					.children("table").hide();

            $.ajax({
                url: 'Admin/Plugins/Products/default.php',
                type: "post",
                cache: false,
                dataType: "json",
                data: {
                    Function: "GetDiameterByShapeAndCapacity",
                    Shape: $("#Products .Options .Shapes .Selected a").attr("value"),
                    Capacity: $("#Products .Options .Capacities select").val()
                },
                success: function (Diameters) {
                    var OptionsCode = '';
                    for (var i = 0; i < Diameters.length; i++) {
                        OptionsCode += "<option value='" + Diameters[i] + "'>" + Diameters[i] + " " + TakZarf.ProductsSearch.Literals.Millimeters + "</option>";
                    }
                    DiametersElement.find("select").html(OptionsCode).end()
							.children(".Loading").hide().end()
							.children("table").show();
                    TakZarf.ProductsSearch.LoadProducts();
                }
            });
        },

        LoadProducts: function () {
            var DataListElement = $("#Products .DataList");
            var DataList = $("#Products .DataList");

            DataList.html("<div class='Loading'></div>");
            DataListElement.children(".Loading").show().end()
					.children(".Data").hide();

            $.ajax({
                url: 'Admin/Plugins/Products/default.php',
                type: "post",
                dataType: "json",
                cache: false,
                data: {
                    Function: "GetProductByShapeAndCapacityAndDiameter",
                    Shape: $("#Products .Options .Shapes .Selected a").attr("value"),
                    Capacity: $("#Products .Options .Capacities select").val(),
                    Diameter: $("#Products .Options .Diameters select").val()
                },
                success: function (Products) {
                    var DataListCode = '';
                    for (var i = 0; i < Products.length; i++) {
                        DataListCode += "<div class='Data'>" +
                                            "<div class='Image'>" +
                                                "<a href='" + TakZarf.ProductsSearch.Literals.DetailPageUrl + "?id=" + Products[i].ID + "' >" +
                                                    "<img src='Contents/Products/Images/Thumbnail_" + Products[i].ImageID + ".jpg' />" +
                                                "</a>" +
                                            "</div>" +
                                            "<div class='Info'>" +
                                                "<a href='" + TakZarf.ProductsSearch.Literals.DetailPageUrl + "?id=" + Products[i].ID + "' >" + Products[i][TakZarf.ProductsSearch.Literals.ProductName] + "</a>" +
                                                "<br/>" + TakZarf.ProductsSearch.Literals.Code + ": " + Products[i].Code +
                                            "</div>" +
                                        "</div>";
                    }

                    DataList.html(DataListCode);

                    DataListElement.children(".Loading").hide().end()
					.children(".Data").show();
                }
            });
        }
    },

    Analytics: {
        Init: function () {
            _gaq = [];
            _gaq.push(['_setAccount', 'UA-26234083-1']);
            _gaq.push(['_setDomainName', 'none']);
            _gaq.push(['_setAllowLinker', true]);
            _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);
            })();
        }
    },

    ProductDetail: {
        Init: function () {
            $(".ProductDetail .ProductDetailPossibleNullValuesWrapper").each(function () {
                if ($(this).text().indexOf("0") === 0) {
                    $(this).text("-");
                }
            });
        }
    }
};

jQuery.cookie = function (key, value, options) {
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

$(document).ready(function () {
    TakZarf.Init();
    $("#TopMenu ul li").hover(function () {
        $(this).children("ul").css('visibility', 'visible');
    });
    $("#TopMenu ul li").mouseleave(function () {
        $(this).find("ul:children").css('visibility', 'hidden');
    });
});
