﻿
window.log = function() {
    log.history = log.history || [];   // store logs to an array for reference
    log.history.push(arguments);
    if (this.console) {
        console.log(Array.prototype.slice.call(arguments));
    }
};

(function($, window) {
    /*
    * Simple Watermark 1.1
    * April 19, 2010
    * Corey Hart @ http://www.codenothing.com
    */
    var placeholder = {
        input: 'placeholder' in document.createElement('input'),
        textarea: 'placeholder' in document.createElement('textarea')
    };
    $.fn.simpleWaterMark = function(mainCSS) {
        return this.each(function() {
            var self = this,
                $input = $(self),
                title = self.getAttribute('title'),
                inplace = self.getAttribute('placeholder'),
                useinplace = !!(inplace && inplace !== ''),
                css = $.metadata ? $input.metadata().watermark : mainCSS;
            if ($.data(self, 'simple-watermark') === true) {
                return;
            }
            $.data(self, 'simple-watermark', true);
            if ($.fn.simpleWaterMark.removeTitle === true) {
                self.removeAttribute('title');
            }
            if ($.fn.simpleWaterMark.HTML5 === true && placeholder[self.nodeName.toLowerCase()]) {
                if (!useinplace) { self.placeholder = title; }
                return;
            }
            if (useinplace) { title = inplace; }
            if ($input.val() === '' && title && title !== '') { $input.addClass(css).val(title); }
            $input.bind({
                'focus.simple-watermark': function() {
                    if ($input.hasClass(css)) {
                        $input.removeClass(css).val('');
                    }
                },
                'blur.simple-watermark': function() {
                    if ($input.val() === '' && title && title !== '') {
                        $input.addClass(css).val(title);
                    }
                }
            })
            .closest('form').bind('submit.simple-watermark', function() {
                if ($input.hasClass(css)) {
                    $input.val('');
                }
            });
            $(window).bind('unload.simple-watermark', function() {
                $input.val('');
            });
        });
    };
    $.fn.simpleWaterMark.HTML5 = true;
    $.fn.simpleWaterMark.removeTitle = true;
     
    (function() {
        var busy,
            isIE6 = /msie|MSIE 6/.test(navigator.userAgent),
            div = $("<div>"),
            content = $("<p>").attr("id", "helpTextContent"),
            outerstruct = div.clone().css({ opacity: 0.9 }).attr("id", "helpTextOuter").hide(),
            struct = outerstruct.append(div.clone().attr("id", "helpText").append(content));

        $.fn.helpText = function(options) {
            options = $.extend({}, $.fn.helpText.defaultOptions, options);
            return this.each(function() {
                var that = this,
                    $that = $(that),
                    hook = options.hook || document.body,
                    text = options.text;

                if (!busy) {
                    busy = true;
                    var helpDiv = struct.clone(),
                        delay = 350,
                        help = {
                            outer: helpDiv,
                            content: helpDiv.find("#helpTextContent")
                        };
                    if (isIE6) {
                        help.outer.addClass("ieSucks");
                        $("html").addClass("ie6sucks");
                    }
                    help.content.html($.metadata ? $that.metadata().text : text ? text : "No input given :(");
                    help.outer.prependTo(hook);

                    $that.bind({
                        "show.help-text": function() {
                            help.outer.slideDown(delay);
                            d = setTimeout(function() {
                                log(d);
                                $that.trigger("hide.help-text");
                            }, 2000 + delay);
                        },
                        "hide.help-text": function() {
                            help.outer.slideUp(delay, function() {
                                busy = false;
                                $that.trigger("cleanup.help-text");
                            });
                        },
                        "cleanup.help-text": function() {
                            $that.unbind(".help-text");
                            help.outer.remove();
                            log($that);
                        },
                        "pinned.help-text": function() {
                            help.outer.addClass("helpTextpinned");
                        }
                    });

                    help.outer.bind({
                        "mouseenter": function() {
                            clearTimeout(d);
                            $that.trigger("pinned.help-text");
                        },
                        "mouseleave": function() {
                            log("out");
                            u = setTimeout(function() {
                                $that.trigger("hide.help-text");
                            }, 200);
                        }
                    });

                    $that.trigger("show.help-text");
                }
            });
        };
        $.fn.helpText.defaultOptions = { text: "No input given :(", hook: document.body, test: "test" };
    })();


    (function() {
        var busy,
            isIE6 = /msie|MSIE 6/.test(navigator.userAgent),
            div = $("<div>"),
            content = $("<p>").attr("id", "helpTextContent"),
            outerstruct = div.clone().css({ opacity: 0.9 }).attr("id", "helpTextOuter").hide(),
            struct = outerstruct.append(div.clone().attr("id", "helpText").append(content));

        $.helpText = function(element, options) {
            var base = this;

            base.$element = $(element);
            base.element = element;

            base.$element.data("helpText", base);

            base.init = function() {
                base.options = $.extend({}, $.helpText.defaultOptions, options);

                var hook = options.hook || document.body,
                    content = options.content;

                if (!busy) {
                    busy = true;
                    var helpDiv = struct.clone(),
                        delay = 350,
                        help = {
                            outer: helpDiv,
                            content: helpDiv.find("#helpTextContent")
                        };

                    if (isIE6) {
                        help.outer.addClass("ieSucks");
                        $("html").addClass("ie6sucks");
                    }

                    help.content.html($.metadata ? base.$element.metadata().content : content ? content : "No input given :(");
                    help.outer.prependTo(hook);

                    base.$element.bind({
                        "show.help-text": function() {
                            help.show(delay);
                            d = setTimeout(function() {
                                base.$element.trigger("hide.help-text");
                            }, 2000 + delay);
                        },
                        "hide.help-text": function() {
                            help.hide(delay, function() {
                                busy = false;
                                base.$element.trigger("cleanup.help-text");
                            });
                        },
                        "cleanup.help-text": function() {
                            base.$element.unbind(".help-text");
                            help.outer.remove();
                            log(base.$element);
                        },
                        "pinned.help-text": function() {
                            help.outer.addClass("helpTextpinned");
                        }
                    });

                    help.outer.bind({
                        "mouseenter": function() {
                            clearTimeout(d);
                            base.$element.trigger("pinned.help-text");
                        },
                        "mouseleave": function() {
                            log("out");
                            u = setTimeout(function() {
                                base.$element.trigger("hide.help-text");
                            }, 200);
                        }
                    });

                    base.$element.trigger("show.help-text");
                }
            };

            base.hide = function() {

            };
            base.show = function() {

                this.outer.slideDown(delay, callback);

            };
            base.cleanup = function() {

            };
            base.pin = function() { 
            };

            help.show = function(delay, callback) {
            };

            help.hide = function(delay, callback) {
            };

            // Sample Function, Uncomment to use
            // base.functionName = function(paramaters){
            // 
            // };

            // Run initializer
            base.init();
        };

        $.helpText.defaultOptions = {
            content: "No input given :(",
            hook: document.body,
            test: "test",
            inline: false
        };

        $.fn.helpText = function(options) {
            return this.each(function() {
                (new $.helpText(this, options));
            });
        };
    })();

})(jQuery, this);

function $(id) { return document.getElementById(id); }

function RegisterUser() {
    $('SubmitUser').style.display = 'none';
    setTimeout('RegisterUserForm();', 1);
}
function RegisterUserForm() {
    $('UserError').innerHTML = "";
    if ($('Password').value.length < 4 || $('Password').value != $('Password2').value)
        $('UserError').innerHTML = "Lösenordet för kort eller stämmer inte.";
    if ($('Name').value.length < 1)
        $('UserError').innerHTML = "Ange ditt namn";
    if ($('LastName').value.length < 1)
        $('UserError').innerHTML = "Ange ditt namn";
    if (!ValidEmail($('Email').value))
        $('UserError').innerHTML = "Felaktig epostadress";
    if ($('Email').value.length < 3)
        $('UserError').innerHTML = "Ange din epost adress";

    if ($('UserError').innerHTML == "") {
        var res = Bv.UserRegister($('Name').value, $('LastName').value, $('Email').value, $('Password').value);
        
        if (res.value != null)
            $('UserError').innerHTML = res.value;
        else
            $('UserError').innerHTML = res.error.Message;
    }
    if ($('UserError').innerHTML == "") {
        $('register_form').innerHTML = "<p>Du kommer få ett e-post innehållande en länk där du bekräftar ditt konto.</p>";
    }
    else
        $('SubmitUser').style.display = '';
}

var UserInfo;
function GetUserInfo() {
    Bv.UserGetInfo(UpdateUserInfo);
}
function UpdateUserInfo(res) {
    UserInfo = res.value;
    if (UserInfo === null) {
        return false;
    }
    else {
        $j("#login").colorbox({ href: "/My/Default.aspx", opacity: 0.35 });
        return true;
    }
}
function InvokeUserItem(i) {
    var item = UserInfo.Items[i];
    if (item.View == "Beskriv")
        window.open("/" + item.Request.View + "?" + item.QueryString);
    else
        window.location = "/" + item.Request.View + "/" + item.Request.Channel + "?" + item.QueryString;
}
function RemoveUserItem(Id) {
    var res = Bv.UserRemoveItem(Id).value;
    GetUserInfo();
    return res;
}
function AddUserItem(req, name) {
    if (!Bv.IsLoggedIn().value)
        return alert("Du måste logga in eller skapa ett nytt konto för att använda denna tjänst.");
    if (typeof ToQuery == "function")
        req.Query = ToQuery();
    Bv.UserAddItem(req, name);
    return true;
}

function AddUserFavourite(id) {
    if (UserInfo == null)
        return alert("Du måste logga in eller skapa ett nytt konto för att använda denna tjänst.");
    Bv.UserAddFavourite(Request, id);
    GetUserInfo();
}
function Login() {
    if ($('LoginEmail').value.length < 2 || $('LoginPassword').value.length < 1) {
        $j('#login_error').show().html("Du måste ange E-post/Kundnummer och lösenord");
        return false;
    }
    var login = Bv.UserLogin($('LoginEmail').value, $('LoginPassword').value);
    if (login.error != null) {
        $j('#login_error').show().html(login.error.Message);
        return false;
    }
    
    var UserId = login.value;
    var expire = "";

    if ($('RememberMe').checked) {
        var date = new Date();
        date.setDate(date.getDate() + 365);
        expire = "; expires=" + date.toGMTString();
    }
    if (UserId != null) {
        document.cookie = "bvuser=" + UserId + expire + "; path=/";
        return true;
    }
    else {
        $j('#login_error').show().html("Fel lösenord / e-post");
        return false;
    }
}
function Logout() {
    document.cookie = "bvuser=; path=/";
}
function SendForgottenPassword(email) {
    if (!ValidEmail(email)) {
        $j('#forgottenResponse').show().html("Ej giltig e-post adress.");
        return false;
    }
    Bv.SendForgottenPassword(email);
    $j('#forgottenResponse').show().html("<strong>Lösenordet är skickat</strong>");
    return true;
}
