﻿String.prototype.endsWith = function(str){return (this.match(str+"$")==str)}

Cufon.replace('h1');

$(document).ready(function () {

    $.preloadCssImages();
    LoadControls();
    BindFormEvents();

    $('a.print-page').click(function (e) {
        e.preventDefault();
        window.print();
    });

    // add a "rel" attrib if Opera 7+
    if (window.opera) {
        if ($("a.bookmark-page").attr("rel") != "") { // don't overwrite the rel attrib if already set
            $("a.bookmark-page").attr("rel", "sidebar");
        }
    }

    $("a.bookmark-page").click(function (event) {
        event.preventDefault();
        var url = window.location;
        var title = document.title;
        if (window.sidebar != null) { // Mozilla Firefox Bookmark
            window.sidebar.addPanel(title, url, "");
        } else if (window.external != null) { // IE Favorite
            window.external.AddFavorite(url, title);
        } else if (window.opera != null) { // Opera 7+
            return false;
        } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
            alert('Press "CTRL + D" or "CMD + D" (for Mac) to add this page to your bookmarks.');
        }
    });

    $('.banner-item-highlight').css({ 'opacity': 0.8 });

    $("#home-banner .banner-items .banner-item a").hover(
        function () {
            if (!$(this).find('.banner-item-highlight').is(':animated')) {
                $(this).find('.banner-item-highlight').animate({ opacity: 1, height: [73, 'swing'] }, 200, 'linear', function () { });
                //$(this).find('.banner-item-text').animate({ bottom: 10 }, 200, 'linear', function () { });
                $(this).find('img').animate({ bottom: 10 }, 200, 'linear', function () { });
            }
        },
        function () {
            $(this).find('.banner-item-highlight').stop().animate({ opacity: 0.8, height: [63, 'swing'] }, 200, 'linear', function () { });
            //$(this).find('.banner-item-text').stop().animate({ bottom: 0 }, 200, 'linear', function () { });
            $(this).find('img').stop().animate({ bottom: 0 }, 200, 'linear', function () { });
        });

//    $("#inner-banner .banner-items .banner-item a").hover(
//        function () {
//            if (!$(this).is(':animated')) {
//                $(this).animate({ height: 111 }, 500, 'swing', function () { });
//            }
//        },
//        function () {
//            $(this).stop().animate({ height: 80 }, 300, 'swing', function () { });
//        });


        $("#inner-banner .banner-items .banner-item a").hover(
        function () {
            if (!$(this).find('.banner-item-highlight').is(':animated')) {
                $(this).find('.banner-item-highlight').animate({ opacity: 0.8, height: [63, 'swing'] }, 200, 'linear', function () { });
                $(this).find('.banner-item-text').animate({ bottom: 0 }, 200, 'linear', function () { });
            }
        },
        function () {
            $(this).find('.banner-item-highlight').stop().animate({ opacity: 0.6, height: [63, 'swing'] }, 200, 'linear', function () { });
            $(this).find('.banner-item-text').stop().animate({ bottom: 0 }, 200, 'linear', function () { });
        });

        $("a.request-callback").click(function (e) {
            e.preventDefault();
            e = $(this);
            e.trigger('blur');
            var value = e.attr('rel');
            show_ajax_loader('body');
            $.get(e.attr('href') + "?" + Math.random(), function (data) {
                hide_ajax_loader('body');
                $('body').append(data);
                $("#success-messages").hide();
                var dialog = $("#callback-dialog");
                handleActiveDialog(dialog);
                $('#callback-dialog form').first().submit(function () {
                    show_ajax_loader(dialog);
                    $.post($(this).attr('action'), $(this).serialize(),
    	                function (data) {
    	                    hide_ajax_loader(dialog);
    	                    var result = GetJsonResult(data);
    	                    if (!result.Successful) {
    	                        $("#error-messages").hide();
    	                        ProcessResult(data);
    	                        $("#error-messages").fadeIn();
    	                    }
    	                    else {
    	                        $("#error-messages").hide();
    	                        ProcessResult(data);
    	                        $("#callback-form").slideUp('slow', function () { $("#success-messages").slideDown(); });
    	                    }
    	                }
                     );
                    return false;
                });
            });
        });

//    $.get("/contact/callback?" + Math.random(), function (data) {
//        $('body').append(data);
//        var dialog = $("#callback-dialog");
//        handleActiveDialog(dialog);
//        $('#callback-dialog form').first().submit(function () {
//            $("#callback-form").height('auto');
//            $("#callback-form").slideUp('slow', function () { $("#callback-form").slideDown('slow'); });
//            return false;
//        });
//    });
});

function show_ajax_loader(container) {
    $(container).append('<div class="ajax-loader"></div>');
}

function hide_ajax_loader(container) {
    $(container).find('.ajax-loader').remove();
}

function LoadControls() {
    $("input.submit").after(function () { return $('<a></a>').attr({ "href": "", "class": "submit-btn btn forinput", "id": $(this).attr('id') }).html($(this).attr('value')); }).remove();
    $('select').JellyfishCustomSelect();
    $('input:checkbox, input:radio').checkbox();
}

function BindFormEvents() {

    var focussed_form;
    $('input').focus(focus_form);
    $('input').blur(unfocus_form);    
    $('select').focus(focus_form);
    $('select').blur(unfocus_form);
    $('a.btn.forinput').focus(focus_form);
    $('a.btn.forinput').blur(unfocus_form);
    $('.select_bg').focus(focus_form);

    $(document).keypress(function (e) {
        if (e.keyCode == 13) {
            submit_form();
        }
    });

    $('a.btn.forinput').click(function (e) {
        e.preventDefault();
        $(this).closest('form').trigger('submit');
    });
}

function focus_form() {
    focussed_form = $(this).closest('form');
}

function unfocus_form() {
    focussed_form = null;
}

function submit_form() {
    $(focussed_form).trigger('submit');
}

/*------------------------------------------------ POP UP DIALOGS -----------------------------------------------------*/
function handleActiveDialog(dialog) {

    LoadControls();
    BindFormEvents();

    $(dialog).hide().css({"z-index": "9999"});
    
    var winH = $(window).height();
    var winW = $(window).width();
    var scrollTop = $(window).scrollTop();

    //Set the popup window to center
    $(dialog).css('top', winH / 2 - $(dialog).height() / 2 + scrollTop);
    $(dialog).css('left', winW / 2 - $(dialog).width() / 2);

    // Display pop up and reinit javascript goodiness
    $("#overlay").css({"height" : $('body').outerHeight() +"px"} ).fadeTo("fast", 0.5).fadeIn("fast", function () { $(dialog).fadeIn(500); });

    $(dialog).find("a.close-btn-trigger").click(function (e) {
        e.preventDefault();
        hide_confirmationpopup(dialog);
    });
    $(dialog).click(function () {
        //hide_confirmationpopup(dialog);
    });
    $("#overlay").click(function () {
        hide_confirmationpopup(dialog);
    });
    $(document).keyup(function (e) {
        if (e.keyCode == 27) {
            $(document).unbind('keyup');
            $(document).unbind('keypress');
            hide_confirmationpopup(dialog);
        }
    });
}

function hide_confirmationpopup(dialog) {
    $(dialog).fadeOut('fast', function (d) {
        $(this).remove();
        $("#overlay").fadeOut('fast', function (e) {            
            $(this).remove();
        });
    });
}

/*------------------------------------------- MVC MODELSTATE HANDLER ------------------------------------------------*/
function GetJsonResult(content) {    
    return content;
}

function ProcessResult(content) {

    var result = GetJsonResult(content);    
    $("#error-messages").empty();    
    //$("#error-messages > ul").empty();
    $(':input').removeClass('input-validation-error');    
    if (result.Successful) {
        $('#error-messages').append('<h4>' + result.Message + '</h4>')
                             .removeClass('error')
                             .addClass('success');
    }
    else {

        $('#error-messages').append('<h4>' + result.Message + '</h4><p>Please fill the highlighted field(s).</p>')
                             .removeClass('success')
                             .addClass('error');

        //$('#error-messages').append('<ul></ul>');
        for (var err in result.Errors) {
            var propertyName = result.Errors[err].PropertyName;
            var errorMessage = result.Errors[err].Error;
            var message = errorMessage;

            $('#' + propertyName).addClass('input-validation-error');
            //$('#error-messages > ul').append('<li>' + message + '</li>');
        }
    }
}
