/**
 * @author nueysan.waldman
 * @author ferenc.radius
 */

$.scriptPath = "./assets/js/";
$.cssPath    = "./assets/css/";
$.requireCache = true;

$.require(["base.js"]);

/**
 * Catch all view (for all urls) will be replaced by correct model
 */
mvc.add(new mvc.Urls("/$", "/index.php$", "/frontend.php$", "/frontend_dev.php$"),
    [
        "jquery/jcarousel.js",
        "swfobject.js",
        "nl.usmedia/carousel_voting.js"
    ], new mvc.Action(
    {
        success: function() {
            createCarouselVote();
        }
    })
);

mvc.add(new mvc.Urls("/magazine/"),
    [
        "nl.usmedia/magazine.js"
    ],
        new mvc.Action(
    {
        success: function() {

            var width  = 900;
            var height = 550;

            var offsetTop  = 0;
            var offsetLeft = 0;

            function calcOffsets() {
                offsetTop  = Math.ceil( ($(window).height() - height) /2 );
                offsetLeft = Math.ceil( ($(window).width()  - width ) /2 );
            }

            $("a.popover").click(function(e){

                e.preventDefault();

                var popover = $('<div id="popover"></div>')
                    .appendTo("body")
                        .hide()
                    .click(function(e) {
                        $('#popover').css('cursor', 'pointer').fadeOut().remove();
                    });

                $('<iframe />')
                    .attr({
                        'src': $(this).attr('href'),
                        'frameborder': '0',
                        'border':      0,
                        'width':       width + 'px',
                        'height':      height + 'px'
                    })
                    .appendTo(popover);

                calcOffsets();

                $(popover)
                    .css(
                        'opacity', '0.75'
                    ).find('iframe').css({
                        'margin-top':  offsetTop + 'px',
                        'margin-left': offsetLeft + 'px'
                    })
                    .end()
                    .fadeIn();


                $(window).resize(function() {
                    calcOffsets();
                    $(popover)
                        .find('iframe').css({
                            'margin-top':  offsetTop + 'px',
                            'margin-left': offsetLeft + 'px'
                        })
                });
            });

        }
    })
);

/**
 * Catch all view (for all urls) will be replaced by correct model
 */
mvc.add(new mvc.Urls(""),
    [
        "nl.usmedia/smartSearch.js",
        "jquery/jquery.equalizecols.js",
        "nl.usmedia/popup.js"
    ], new mvc.Action(
    {
        success: function() {

            $('#search_container').smartSearch();
            $('#search_container_side').smartSearch();
            $('#search_container_homepage').smartSearch();

            $('#homepage_standpunten_container .standpunt_wrapper').equalizeCols();
            //$('#highlight_container .column').equalizeCols();

            $("a[href*='url=']:not(.popup)")
                .attr('target','_blank')
                .attr('title','Deze link opent in een nieuw venster');

            $("a[href^='http://']:not(.popup)")
                .not("a[href^='http://" + location.hostname + "']")
                .attr('target','_blank')
                .attr('title','Deze link opent in een nieuw venster');

            $("a.popup").popup(460, 640);
            $("<hr />").addClass("clearfix").insertBefore("#overview_container .three .column:nth-child(3n+1)");
            // $('#overview_container .three .column:nth-child(3n+1)').css('clear', 'left');
        }
    })
);

/**
 * article pages
 */
mvc.add(new mvc.Urls("standpunt/[0-9]+", "actueel/[0-9]+", "word-lid", "vvd-in-de-buurt/buitenland", "detail/[0-9]+", "content/[0-9]+"),
    [
        "jquery/jquery.json.js",
        "jquery/jquery.rating.js",
        "nl.usmedia/printButton.js"

    ], new mvc.Action(
    {
        success: function() {

            var applyRatingStars = reApplyRatingStars = function() {
                $('input.rating').rating({
                    callback: function(value, link){

                        var choice = $(this).parent().find('input.rating').index(this)+1;
                        var self = this;
                        $.post("./sendRating", {
                            'rating': choice,
                            'id': $("#contentId").val()
                        }, function(data) {
                            $('.star-rating-control').remove();
                            $(self).parent()
                                   .find('input.rating').attr('disabled', 'disabled').removeClass('star-rating-applied')
                                    .removeAttr('checked').eq(data.rating-1).attr('checked', 'checked');

                            reApplyRatingStars();
                        }, 'json');
                    }
                });
            };
            applyRatingStars();

            /*********************************** print button ****************************************/
            $("#sharing_container").printButton('Printen');


            /***************************** doorsturen / delen switch **********************************/
            $("#sharing_container li").each(function() {
                (function(self) {
                    $(self).hide();

                    var title = $(self).find("h4").css('cursor', 'pointer');
                    $(title).insertAfter('#print_title').click(function() {
                        $("#sharing_container li").not(self).removeClass('switch_open').hide(function() {

                        if($(self).is('.switch_open')) {
                            $(self).removeClass('switch_open').fadeOut();
                        } else {
                            $(self).addClass('switch_open').fadeIn()
                        }
                        });
                    });

                })(this);
            });
            $("#sharing_container li.active").show();


            /****************************************** TAF *********************************************/
            $("#forward form").submit(function(e) {
                e.preventDefault();

                $(this).find('div.text_wrapper').removeClass('error');

                $.post(
                    './taf',
                    {
                        'content_id':          $("#content_id").val(),
                        'sender_name':         $("#sender_name").val(),
                        'sender_email':        $("#sender_email").val(),
                        'receiver_name':       $("#receiver_name").val(),
                        'receiver_email':      $("#receiver_email").val(),
                        'message':             $("#message").val()
                    },
                    function(data) {
                        for(prop in data) {
                            $('#' + prop).parent('div').addClass('error');
                        }

                        if( data.succes ) {
                            $("#receiver_name").val('');
                            $("#receiver_email").val('');
                            $("#message").val('');

                            $("#forward > div").prepend(data.succes);
                        }
                    },
                    'json'
                );
            });


            /*************************************** taf preview *******************************************/
            $("#preview").popup(800, 600);


            /*********************************** reaction toggle *******************************************/
            if( $("#related_container").find('div.reaction').length > 0 ) {
                $("#related_container div h4").css('cursor', 'pointer').click(function() {
                    if($(this).parent().hasClass('collapsed')) {
                        $(this).parent().find("div.wrapper").slideDown(125).end().removeClass('collapsed');
                    } else {
                        $(this).parent().find("div.wrapper").slideUp(125).end().addClass('collapsed');
                    }
                });
            }

        }
    })
);


/**
 * styled select / forms
 */
mvc.add(new mvc.Urls("/zoeken", "search-form.html", "form-tests.html", "word-lid", "aanmelden", "registreren", "registration"),
    [
        "nl.usmedia/styledSelect.js"
    ], new mvc.Action(
    {
        success: function() {

            $("#search_filters select, #lid_form select, #cvform select, #registerform select:not(#childreninfo select)").styledSelect({

                afterOpenCallback: function() {
                    $(this).parent().css('z-index', '1000');
                },
                afterCloseCallback: function() {
                    $(this).parent().css('z-index', '0');
                }
            });

            function handleCountChildren(choice) {
                var maxChildren = $("#childreninfo select option").length;
                for(var i = 0; i < maxChildren; i++) {
                    if(i <= choice && i > 0) {
                        $("#child_age_" + i).parent().show();
                        $("#child_name_" + i).parent().show();
                    } else {
                        $("#child_age_" + i).parent().hide();
                        $("#child_name_" + i).parent().hide();
                    }
                }
            }

            $("#childreninfo select").styledSelect({

                afterOpenCallback: function() {
                    $(this).parent().css('z-index', '1000');
                },
                afterCloseCallback: function() {
                    $(this).parent().css('z-index', '0');
                },
                afterChangeCallback: function(settings, container, select) {
                   handleCountChildren($(select).val());
                },
                initCallback: function(settings, container, select) {
                   handleCountChildren($(select).val());
                }
            });

            $("#member_birthdate_year, #registration_paper_entry_geboortedatum_year")
                .next("div.styledSelect").addClass("year");

            /****************************************************************************************************
             * price info
             */
            function parsePrices() {
                var totalPrice = 0.00;

                // show machtiginginfo when a price is selected
                if($("#priceinfo input[type='checkbox']:checked").length == 0) {
                    $("#machtiginginfo").hide();
                } else {
                    $("#machtiginginfo").show();
                }

                // count total price ( fix floating point bug by rounding it to 2)
                $("#priceinfo input[type='checkbox']:checked").each(function() {
                    var price = $(this).parent().find('.price').text().replace(',', '.').match(/[0-9.]+/)[0];
                    totalPrice += parseFloat( price );
                });
                totalPrice = totalPrice.toFixed(2);
                $('#total_price span, #machtiginginfo .price span').text(totalPrice);
            }

            $("#priceinfo input[type='checkbox']").click(function() {
                parsePrices();
            });

            // handle on load
            parsePrices();
        }
    })
);

/**
 * scrolling standpunten
 */
mvc.add(new mvc.Urls("standpunten/overzicht", "standpunten.html"),
    [
        "jquery/scrollTo.js"
    ], new mvc.Action(
    {
       success: function() {
            $(".standpunten_index a, .link_up a").click(function(e) {
                e.preventDefault();
                $.scrollTo(this.hash, 500);
            });
       }
    })
);


mvc.add(new mvc.Urls("vvd-in-de-buurt", "maps.html"),
    [
        "nl.usmedia/LocateMap.js"
    ], new mvc.Action(
    {
       success: function() {

            /* gmaps form toggle*/
            $("#gmaps_options h4").css('cursor', 'pointer').click(function() {
                if($(this).parent().hasClass('collapsed')) {
                    $(this).parent().find("#gmaps_form").slideDown(125).end().removeClass('collapsed');
                } else {
                    $(this).parent().find("#gmaps_form").slideUp(125).end().addClass('collapsed');
                }
            });

           var map = new LocateMap("gmap", "Nederland", "./locator/locator.php", "#gmaps_search_results");
           map.init("Den Haag Laan Copes van Cattenburch 52");
           map.setSearchFields(["#zipcode", "#city"]);
       }
    })
);

/**
 * Cufon font replacement needs to occur asap --Nuey
 */
mvc.add(new mvc.Urls(""),
    [
        //"vvd.font.js"  is now part of base.js
    ], new mvc.Action(
    {
        onload: function() {
            Cufon.replace('h1:not(#homepage_container h1), h2, h3, #highlight_container dt, #search_container_homepage legend');
            Cufon.replace('#navigation li.active ul a, #signup_component a', { hover: true });
        }
    })
);
