/*
 * NIDA - Global Javascript
 *
 * global.js
 * author: Squiz Australia
 */
/*
 * Table of Contents
 *
 *  1. Global Functions
 *
 *  2. Document Ready
 *      2.1 Adding Classes
 *      2.2 Main Nav - No children classes
 *      2.3 Accordion
 *      2.4 Tabs
 *      2.5 Date Picker
 *      2.6 File Input Label
 *      2.7 Gallery Box Hover States
 *      2.8 Pagination
 *      2.9 Home Menu Boxes
 *      2.9 Sidebar
 *      2.10 Carousel
 *      2.11 Lightbox
 *      2.12 Page Tools
 *      2.13 Fix Nested list styles
 *      2.14 Calculates height for footer reveal
 *      2.15 Activates the search box in header
 *      2.16 Smooth scroll on Back to top button
 *      2.17 Custom style on select dropdowns
 *      2.18 placeholder fix for ie9 and below
 *      2.19 Maps
 *      2.20 Calendar date picker image
 *      2.21 Home subscribe form
 *
 *  3. Additional Plugins
 *      3.1 Print Preview
 */
/*----------------------------------------
1. Global Functions
----------------------------------------*/
//This function makes the selected elements all the same width / height
function makeSame(dimension, elem, notElem) {
    if ($(elem).length) {

        var elemHeight;
        var elemWidth;

        if (notElem) {
            var selectedElems = $(elem).not(notElem);
        } else {
            var selectedElems = $(elem);
        }

        if (selectedElems) {

            //check for height
            if (dimension === 'height') {

                selectedElems.each(function () {

                    if (elemHeight != undefined) {

                        if ($(this).height() > elemHeight) {

                            elemHeight = $(this).height();

                        }

                    } else {

                        elemHeight = $(this).height();

                    }

                });

                selectedElems.css('min-height', elemHeight + 'px');

                //check for width
            } else if (dimension === 'width') {

                selectedElems.each(function () {

                    if (elemWidth != undefined) {

                        if ($(this).width() > elemWidth) {

                            elemWidth = $(this).width();

                        }

                    } else {

                        elemWidth = $(this).width();

                    }

                });

            }

            selectedElems.css('width', elemWidth + 'px');

        }

    }

}

/*----------------------------------------
2. Document Ready
----------------------------------------*/

$(document).ready(function () {

    /* ----- 2.1 Adding Classes ----- */

    //add js class
    $('body').addClass('js');

    //add first classes
    $('#main-nav > li:first-child').addClass('first-child');
    $('table th:first-child').addClass('first-child');

    //add last classes
    $('.header-links li:last-child').addClass('last-child');
    $('#main-nav > li:last-child').addClass('last-child');
    $('table th:last-child').addClass('last-child');
    $('#tabs > ul li:last-child').addClass('last-child');
    $('.locations .locations-list li:last-child').addClass('last-child');
    $('#content .profiles .profile:last-child').addClass('last-child');

    $('.main .row .box:last-child').addClass('last-child');

    //add even classes
    $('table tr:nth-child(even)').addClass('even-child');
    $('.gallery-list-wrapper .box.gallery:nth-child(even)').addClass('even-child');

    //add misc classes
    $('table tr:last-child td:first-child').addClass('last-tr-first-td');
    $('table tr:last-child td:last-child').addClass('last-tr-last-td');

    /* ----- 2.2 Main Nav - No children classes ----- */
    $('#main-nav > li').each(function(){
      var $this = $(this);
      if($this.find('> .dropdown').length == 0){
        $this.addClass('no-children');
      }
    })

    /* ----- 2.3 Accordion ----- */

    $(".accordion").accordion({
        heightStyle: "content", active: false, collapsible: true
    });

    /* ----- 2.4 Tabs ----- */
    $(".tabs-default").tabs();

    /* ----- 2.5 Date Picker ----- */
    var datePickerOptions = {
        showOn: "button",
        buttonText: "Show date picker",
        dateFormat: "dd/mm/yy"
    };
    $('#date-from').datepicker(datePickerOptions);
    $('#date-to').datepicker(datePickerOptions);

    /* ----- 2.6 File Input Label ----- */
    $('.button input[type="file"]').change(function () {
        var filename = $(this).val();
        $(this).parent().siblings('.filename').remove();
        $(this).parent().after('<span class="filename">' + filename + '</span>');

    });

    /* ----- 2.7 Gallery Box Hover States ----- */





    /* ----- 2.8 Pagination ----- */

    var paginationMax;
    if ($('.content-inner .pagination').length) {
        paginationMax = 5;
    } else {
        paginationMax = 7;
    }


    var paginationMiddle = Math.floor(paginationMax / 2);


    var paginationLen = $('.pagination li a').length;
    var activePagIndex;
    $('.pagination li a').each(function (index) {

        if ($(this).hasClass('active') && index >= paginationMiddle) {
            activePagIndex = index;
            //break out of the loop
            return false;
        }
    });

    $('.pagination li a').each(function (index) {

        if (activePagIndex + paginationMiddle < paginationLen) {

            if (index < activePagIndex - paginationMiddle) {
                $(this).closest('li').hide();
            }

        } else {
            if (index < activePagIndex - paginationMax + (paginationLen - activePagIndex)) {
                $(this).closest('li').hide();
            }
        }
    });

    /* ----- 2.9 Home Menu Boxes ----- */

    makeSame('height', $('.home .box.menu'));



    /* ----- 2.10 Carousel ----- */
    var initBigSlider = function($slider){
        $slider.slick({
            slide:'li',
            slidesToShow: 1,
            slidesToScroll: 1,
            autoplay: true,
            dots: true,
            autoplaySpeed: 4000,
            speed: 1000,
            onBeforeChange: function(){
                $slider.find('iframe').remove();
            }
        });

        $sliderSlidesLinks = $slider.find('li > a');
        $sliderSlidesLinks.click(function(){
            $slider.slickPause();
            var $this = $(this);
            var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
            var match = $this.attr('href').match(regExp);
            if (match && match[2].length == 11){
                var youtubeID = match[2];

                var iframeSrc = 'http://www.youtube.com/embed/' + youtubeID + '?rel=0&autoplay=1&wmode=transparent';
                $this.after('<iframe src="' + iframeSrc + '" frameborder="0" allowfullscreen></iframe>');
                return false;
            }
        });
    }
    //init homeslider
    if($('.big-slider').length){initBigSlider($('.big-slider'));}


    $('.internal-slider').slick({
        slide:'li',
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        dots: true,
        autoplaySpeed: 4000,
        speed: 1000
    });



    /* ----- 2.11 Lightbox ----- */
    $('.open-lightbox').click(function () {
        $('#overlay, #loader').show();

        //load the gallery content
        var ajaxUrl = $(this).attr('href') + '?SQ_PAINT_LAYOUT_NAME=gallery-content-layout&SQ_DESIGN_NAME=blank#content';

        var $lightboxContent = $('#lightbox .lightbox-content');

        $lightboxContent.load(ajaxUrl, function () {
            //show lightbox
            $('#loader').hide();
            $('#lightbox').show();

            //init lightbox slider
            if($('.popup-gallery-slider').length){initBigSlider($('.popup-gallery-slider'));}
        });

        $('.lightbox-exit').click(function () {
            $('#overlay, #lightbox').hide();
        });
        return false;
    });

     /* ----- 2.12 Page Tools ----- */

     $('#back a').bind('click', function() {
        $('html,body').animate({ scrollTop: $("#page-wrapper").offset().top }, 500);
        return false;
    });

    $('#page_functions ul').append('<li id="print"><a title="Print preview" class="print-preview">Print preview</a></li>');
    $('a.print-preview').printPreview();

    /* ----- 2.13 Fix Nested list styles ----- */





    /* ----- 2.14 Calculates height for footer reveal ----- */



    /* ----- 2.15 Activates the search box in header ----- */
    $('.search-open-btn , .site-search-text').click(function(){
        $('#search-form').toggleClass('form-open');
        $( "#site-search-field" ).focus();
    });

    /* ----- 2.16 Smooth scroll on Back to top button ----- */
    $('a.back-to-top').click(function() {
        $('html,body').animate({
          scrollTop: 0
        }, 1000);
        return false;
    });

    /* ----- 2.17 Custom style on select dropdowns ----- 
    $('select').customSelect();

    /* ----- 2.18 placeholder fix for ie9 and below ----- */

    jQuery(function() {
    jQuery.support.placeholder = false;
    webkit_type = document.createElement('input');
    if('placeholder' in webkit_type) jQuery.support.placeholder = true;
    });
    $(function() {

    if(!$.support.placeholder) {

    var active = document.activeElement;

    $(':text, textarea, :password').focus(function () {

    if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) && ($(this).attr('placeholder') != '') && $(this).val() == $(this).attr('placeholder')) {
    $(this).val('').removeClass('hasPlaceholder');
    }
    }).blur(function () {
    if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) && ($(this).attr('placeholder') != '') && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
    $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
    }
    });

    $(':text, textarea, :password').blur();
    $(active).focus();
    $('form').submit(function () {
    $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
    });
    }
    });


    /* ----- 2.19 Maps ----- */

    if($('#nida-map').length) {
        var map;
        var myLatLng = new google.maps.LatLng(-33.915973, 151.225692);
        var myMapType = 'custom_style';

        function initialize() {

          var featureOpts = [
            {
              "stylers": [
                { "visibility": "on" },
                { "saturation": -100 }
              ]
            },{
              "featureType": "poi.park",
              "stylers": [
                { "gamma": 1.54 }
              ]
            },{
              "featureType": "road.highway",
              "elementType": "geometry.fill",
              "stylers": [
                { "lightness": 51 }
              ]
            }
          ];
          var image = '/nida_files/map-marker.png';
          var mapOptions = {
            zoom: 17,
            center: myLatLng,
            disableDefaultUI: true,
            mapTypeControlOptions: {
              mapTypeIds: [google.maps.MapTypeId.ROADMAP, myMapType]
            },
            mapTypeId: myMapType
          };

          map = new google.maps.Map(document.getElementById('nida-map'), mapOptions);
          var myMarker = new google.maps.Marker({
              position: myLatLng,
              map: map,
              title: "National Institute of Dramatic Art",
              icon: image
          });

          var styledMapOptions = {
            name: 'Custom Style'
          };

          var customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions);
          map.mapTypes.set(myMapType, customMapType);
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    }


    /* ----- 2.20 Calendar date pickers ----- */
    $('.filter-date-range img').attr('src', 'http://' + location.host + '/__data/assets/image/0015/13056/calendar.gif');

    //CUSTOM SELECT not showing anything when date clicked
    //override date picker function so that it populates the custom select
    var popupSelectInit = function(selectQuery){
            var $select = $(selectQuery);
            var $customSelect = $select.next('.customSelect');
            var $customSelectInner = $customSelect.find('.customSelectInner');
            $customSelect.addClass('customSelectChanged');
            var newVal = $select.find(' option:selected').text();
            $customSelectInner.text(newVal);
    }

    var popupClickInit = function(fromTo){
        var $yearInput = $('#queries_daterange_fquery_' + fromTo + 'value_y');
        var $yearSelect = $('<select></select>');
        var thisYear = new Date().getUTCFullYear();
        var selectedYear = null;
        if($yearInput.val()){
            selectedYear = parseInt($yearInput.val());
        }
        $yearSelect.append('<option value=""></option>');
        for(var x=0;x<3;x++){
            var yr = thisYear + x;
            if(yr == selectedYear){
                $yearSelect.append('<option value="' + String(yr) + '" selected>' + String(yr).substr(2,2) + '</option>');
            }else{
                $yearSelect.append('<option value="' + String(yr) + '">' + String(yr).substr(2,2) + '</option>');    
            }
        }

        $yearInput.remove();
        $yearSelect.attr('name','queries_daterange_fquery_' + fromTo + 'value[y]');
        $yearSelect.attr('id','queries_daterange_fquery_' + fromTo + 'value_y');
        $yearSelect.insertAfter($('#queries_daterange_fquery_' + fromTo + 'value_m').next());
        $yearSelect.customSelect();


        window['queries_daterange_fquery_' + fromTo + '_cal'].dayClick = function c_dayClick(day, mon, year) {
            if (this.onDayClick != null) {
                this.onDayClick(day, mon, year, this.prefix);
                if (this.popup) this.hide();
                popupSelectInit('#queries_daterange_fquery_' + fromTo + 'value_d');
                popupSelectInit('#queries_daterange_fquery_' + fromTo + 'value_m');
                popupSelectInit('#queries_daterange_fquery_' + fromTo + 'value_y');
            }
        }
    }

    if(window.queries_daterange_fquery_to_cal && window.queries_daterange_fquery_from_cal){
        popupClickInit('from');
        popupClickInit('to');
    }

    /* ----- 2.21 Home subscribe form ----- */
    $('.subscribe form input[type="submit"]').click(function(e){
        e.preventDefault();
        var url = "https://nida.wufoo.com/forms/sign-up-to-our-enews/";
        var fullName = $('.subscribe form input#fullname').val();
        var email = $('.subscribe form input#email').val();
        if(fullName || email) url += "def/";
        if(fullName) url += "field1=" + fullName;
        if(fullName && email) url += "&";
        if(email) url += "field3=" + email;
        document.location = url;
    });



});//end $(document).ready()

/*----------------------------------------
3. Additional plugins
----------------------------------------*/

/* --- 3.1 Print Preview --- */

(function($){$.fn.printPreview=function(){var elements=this;return(elements.each(function(i){var printLink=$(this);var screenSheet=$("link[media='screen']");var printSheet=$("link[media='print']");var previewSheet=document.createElement('link');$(previewSheet).attr({href:printSheet.attr('href'),media:'screen',type:'text/css',rel:'alternate stylesheet',title:'print preview'});document.getElementsByTagName("head")[0].appendChild(previewSheet);previewSheet=$("link[title='print preview']").load();previewSheet.each(function(i){this.disabled=true;});var printPreviewMessage=$('<div id="preview-message"><h3>Print preview</h3><a href="#" id="preview-print">Print this page</a> | <a href="#" id="turnoff-print">Return to the normal view</a></div>');$("head").append('<style type="text/css" media="print"> #preview-message { display: none !important; } </style>');printLink.click(function(){$("body").fadeOut("fast",function(){screenSheet.each(function(){this.disabled=true;});previewSheet.each(function(){this.disabled=false;});$(this).fadeIn("slow");$('html, body').animate({scrollTop:0},'fast');$("body").prepend(printPreviewMessage);$("#preview-message").hide().slideDown("slow");$("a#turnoff-print").bind("click",function(){$("body").fadeOut("fast",function(){$("#preview-message").remove();screenSheet.each(function(){this.disabled=false;});previewSheet.each(function(){this.disabled=true;});$(this).fadeIn("slow");});return false;});$("a#preview-print").bind("click",function(){window.print();return false;});});return false;});}));}})(jQuery);
