﻿var KinoAsync =
{
    ExecuteControl: function(control, targ, keys, vals) {

        BlockPage();
        var args = {
            control: control,
            keys: (keys == null ? [] : keys),
            vals: (vals == null ? [] : vals)
        };
        window.setTimeout(function() {
            $.ajax({
                type: "POST",
                data: $.toJSON(args),
                url: "/Webservices/AjaxMethods.asmx/ExecuteControl",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    targ.show();
                    targ.html(data.d);
                },
                complete: function() {
                    UnBlockPage();
                }
            });
        }, 1);
    }
};

/*
Create the object needed by $.ajax. Set block to true if the UI should be blocked
while the ajax finishes.
*/
var CreateAjaxCall = function(url, data, s, block) {
    return {
        type: 'POST',
        url: url,
        data: $.toJSON(data),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        beforeSend: function(req) {
            if (block) {
                BlockPage();
            }
        },
        success: function(msg) {
            if (s) {
                s(msg.d);
            }
        },
        error: function(req, status, ex) {
            try {
                console.log(req, status, ex);
            }
            catch (e) {
            }
            if (block) {
                UnBlockPage();
            }
        },
        complete: function(req, status) {
            if (block) {
                UnBlockPage();
            }
        }
    };
};

/*
    Send the user to the error page with the errorCode as parameter.
    Mainly used when calling ajax stuff in the ticketflow.
*/
var RedirectToErrorPage = function(errorCode) {
    var url = window.location.toString();
    if (url.split('?').length > 1) {
        url += '&';
    }
    else {
        url += '?';
    }
    url += 'errorid=' + errorCode;
    window.location = url;
};


var TipFriend =
{

    show: function(scid) {
        try {
            var divid = "xx" + (new Date().getTime());
            $.fn.lightbox.start2('<div id="' + divid + '"></div>', 440, 315);
            KinoAsync.ExecuteControl(
                "~/Layouts/Common/TellAFriend.ascx",
                $('#' + divid),
                ["runajaxed", "scid", "divid"],
                ["true", scid, divid]
            );
        }
        catch (eee) { }
    },

    submitClick: function(ids, scid, divid) {
        var values = [];
        for (var i = 0; i < ids.length; i++) {
            values[i] = $('#' + ids[i]).val();
        }

        ids.push("runajaxed");
        values.push("true");
        ids.push("scid");
        values.push(scid);
        ids.push("divid");
        values.push(divid);
        KinoAsync.ExecuteControl(
            "~/Layouts/Common/TellAFriend.ascx",
            $('#' + divid),
            ids,
            values
        );
    }
};

var LoginTicketFlowOverlay =
{
    show: function(scid) {

        var divid = "xx" + (new Date().getTime());
        $.fn.lightbox.start2('<div id="' + divid + '"></div>', 440, 315);
        KinoAsync.ExecuteControl(
                "~/Layouts/Ticketflow/Overlay/Login.ascx",
                $('#' + divid),
                ["runajaxed", "scid", "divid"],
                ["true", scid, divid]
            );

    },

    submitClick: function(ids, scid, divid) {
        var values = [];
        for (var i = 0; i < ids.length; i++) {
            values[i] = $('#' + ids[i]).val();
        }

        ids.push("runajaxed");
        values.push("true");
        ids.push("scid");
        values.push(scid);
        ids.push("divid");
        values.push(divid);
        KinoAsync.ExecuteControl(
            "~/Layouts/Ticketflow/Overlay/Login.ascx",
            $('#' + divid),
            ids,
            values
        );
    }
};

var AttachBiozone =
{

    show: function(scid) {
        try {
            var divid = "xx" + (new Date().getTime());
            $.fn.lightbox.start2('<div id="' + divid + '"></div>', 440, 315);
            KinoAsync.ExecuteControl(
                "~/Layouts/UserProfile/Biozonen.ascx",
                $('#' + divid),
                ["runajaxed", "scid", "divid"],
                ["true", scid, divid]
            );
        }
        catch (eee) { }
    },

    submitClick: function(ids, scid, divid) {
        var values = [];
        for (var i = 0; i < ids.length; i++) {
            values[i] = $('#' + ids[i]).val();
        }

        ids.push("runajaxed");
        values.push("true");
        ids.push("scid");
        values.push(scid);
        ids.push("divid");
        values.push(divid);
        KinoAsync.ExecuteControl(
            "~/Layouts/UserProfile/Biozonen.ascx",
            $('#' + divid),
            ids,
            values
        );
    }
};

var MakeImageInputClickOnce = function(buttonid) {
    var b = document.getElementById(buttonid);
    var oldonclick = b.onclick;
    b.onclick = function() {
        oldonclick();
        this.onclick = function() { return false; }
    };
}

var BlockPage = function() {
    var wnd = $(window);
    var doc = $(document);
    var pTop = doc.scrollTop();
    var pLeft = doc.scrollLeft();
    pLeft += (wnd.width() - 50) / 2;
    pTop += (wnd.height() - 50) / 2;
    $(document.body).block({
        message: '<div style="height: 16px; margin: 17px 17px 17px 17px;"><img src="/Layouts/images/ajax-loader.gif" /></div>',
        css: {
            top: pTop + 'px',
            left: pLeft + 'px',
            color: '#000',
            border: '3px solid #aaa',
            backgroundColor: '#fff',
            cursor: 'default'
        },
        overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.6,
            cursor: 'default'
        }
    });
};

var UnBlockPage = function() {
    $(document.body).unblock();
};

var ExecThumb = function(thumbCode, up, entityId) {
    $.ajax({
        type: "POST",
        data: "{'thumbCode': " + thumbCode + ", 'up': " + up + ", 'entityId': " + entityId + "}",
        url: "/Layouts/AjaxPages/Thumbs.aspx/SetThumbUpDown",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            location.reload();
        },
        error: function(e) {
        }
    });
};

var GetThumbValue = function(thumbId, thumbUp, thumbDown, entityId, up) {
    $.ajax({
        type: "POST",
        data: "{'entityId': '" + entityId + "', 'up': " + up + "}",
        url: "/Layouts/AjaxPages/Thumbs.aspx/GetThumbValue",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            $('#' + thumbId).text(data.d);
            $.ajax({
                type: "POST",
                data: "{'entityId': '" + entityId + "'}",
                url: "/Layouts/AjaxPages/Thumbs.aspx/HasThumbBeenSet",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    if (data.d) {
                        $('#' + thumbUp).attr('disabled', 'disabled');
                        $('#' + thumbDown).attr('disabled', 'disabled');
                    }
                },
                error: function(e) {
                }
            });
        },
        error: function(e) {
        }
    });

};

var CheckEmailAvailability = function(sender, args) {
    var ajaxArgs = { email: args.Value };
    var emailInUse = false;
    $.ajax({
        type: "POST",
        data: $.toJSON(ajaxArgs),
        async: false,
        url: "/Webservices/TicketService.asmx/IsEmailAvailable",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            emailInUse = data.d;
        },
        complete: function() {
            //UnBlockPage();
        }
    });
    args.IsValid = emailInUse;
};

// Passwords must be 4 chars length
var CheckPasswordLength = function(sender, args) {
    if (args.Value.length < 4) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}

MyPageTab =
{
    navigate: function(idx) {
        KinoAsync.ExecuteControl("~/layouts/Tabs/MyPage.ascx", $("#mypage"), ["mypagepastbookingpageindex"], [idx]);
    }
};

$(document).ready(function() {
    $('.trailerbutton').each(function(i) {
        var b = $(this);

        b.mouseover(function(e) {
            if (b.hasClass('aboutmovie'))
                b.addClass('trailerbuttonaboutmovieactive');
            if (b.hasClass('tickets'))
                b.addClass('trailerbuttonticketsactive');
        });

        b.mouseout(function(e) {
            b.removeClass('trailerbuttonaboutmovieactive').removeClass('trailerbuttonticketsactive');
        });
        b.click(function(event) {

            try {
                var link = $('a', b);
                if (link.attr('onclick') != null)
                    link.triggerHandler('click');
                else {
                    location = link.attr('href');
                }
            }
            catch (z) {
            }
        });
    });
});

(function($) {
$.fn.movieRater = function(options) {
        var defaults = {
            callback: null
        };

        var options = $.extend({}, defaults, options);
        var oldRating = $(this).attr('kino:oldrating');
        var movieId = $(this).attr('kino:movieid');
        var url = $(this).attr('kino:url');
        var forceReload = $(this).attr('kino:forceload');
        var rating = oldRating;
        var timerhandle = null;
        var $this = this;
        var stars = $(this).find('img');
        var blocked = false;

        this.initialize = function() {
            for (var i = 0; i < stars.length; i++) {
                stars.eq(i).starnumber = i;
            }
            $(this).mousemove(function() {
                $this.clearTimeout();
            });
            stars.each(function(i) {
                $(this).mouseover(function(event) {
                    $this.clearTimeout();
                    $this.updateStars(stars.index(this));
                });
            });
            $(this).mouseout(function() {
                $this.timerhandle = setTimeout($this.resetStars, 100);
            });
            $(this).click(function() {
                if (blocked)
                    return false;
                blocked = true;
                var conf = (oldRating == -1 ? "Vil du gemme din vurdering på " + rating + " stjerne" :
                        "Vil du ændre din vurdering til " + rating + " stjerne");
                if (rating > 1)
                    conf += "r";
                conf += "?";
                if (confirm(conf)) {
                    oldRating = rating;
                    if (forceReload == 'true') {
                        top.location = url + "?rating=" + rating;
                        blocked = false;
                    }
                    else {
                        BlockPage();
                        window.setTimeout(
                        function() {
                            $.ajax({
                                type: "POST",
                                url: "/Webservices/AjaxMethods.asmx/UpdateMovieRating",
                                data: "{movieid: " + movieId + ", rating: " + rating + "}",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function(res) {
                                    if (options.callback != null) {
                                        options.callback($this);
                                    }
                                    else if (rating != -1) {
                                        $this.updateStars(rating - 1);
                                    }
                                },
                                complete: function() {
                                    UnBlockPage();
                                    blocked = false;
                                }
                            });
                        },
                        1
                    );
                    }
                }
                else {
                    blocked = false;
                }
            });
            if (rating != -1)
                $this.updateStars(rating - 1);
        };

        this.updateStars = function(i) {
            rating = i + 1;
            for (var x = 0; x < 6; x++)
                stars.eq(x).attr('src', '/layouts/images/stars/big_star_' + (x <= i ? '1' : '0') + '.png');
        };

        this.resetStars = function() {
            $this.updateStars(oldRating - 1);
        };

        this.clearTimeout = function() {
            if ($this.timerhandle != null) {
                clearTimeout($this.timerhandle);
                $this.timerhandle = null;
            }
        }

        return this.initialize();
    };
})(jQuery);
