/**
 * @package Common / Bundeled Scripts
 * @version 1.0
 * @author Benjamin Sinke
 */

 window.weathercondition = [];
 window.weathercondition['01d'] = 'Zonnig';
 window.weathercondition['01n'] = 'Helder';
 window.weathercondition['02d'] = 'Half bewolkt';
 window.weathercondition['02n'] = 'Half bewolkt';
 window.weathercondition['03d'] = 'Zwaar bewolkt';
 window.weathercondition['03n'] = 'Zwaar bewolkt';
 window.weathercondition['04d'] = 'Bewolkt';
 window.weathercondition['04n'] = 'Bewolkt';
 window.weathercondition['09d'] = 'Regen';
 window.weathercondition['09n'] = 'Regen';
 window.weathercondition['10d'] = 'Buien';
 window.weathercondition['10n'] = 'Buien';
 window.weathercondition['11d'] = 'Onweersbuien';
 window.weathercondition['11n'] = 'Onweersbuien';
 window.weathercondition['13d'] = 'Sneeuwbuien';
 window.weathercondition['13n'] = 'Sneeuwbuien';
 window.weathercondition['50d'] = 'Mistig';
 window.weathercondition['50n'] = 'Mistig';

 /* BRS @ 16 05 2018 - Move to new APP style setup */

 var onweerOnline = {
     callable: {

         clickForumTopicButton: function(_html) {
             var _action = _html.find('.def_button.antwoorden');

             _action.click(function(e) {
                 if(_html.find('.oo-top-bar-user.notloggedin').length) {
                     e.preventDefault();
                     onweerOnline.stashed.showLoginDialog(_html);
                 }
             });
         },

         clickLoginSubmit: function(_html) {
             $(document).on('click.loginButton', '.dialog-login', function(e) {
                 e.preventDefault();

                 var _this = $(this);
                 _this.parent().find('form').submit();
             });
         },

         controlHeaderPager: function(_html) {
             _html.find('.oo-news-box-item:first').fadeIn();

             var _index = 0;
             var _maxItems = 3;
             var _action = _html.find('.oo-slider-prev, .oo-slider-next');

             _action.click(function(e) {
                var _this = $(this);

                if(e.originalEvent) {
                    clearInterval(_autoPage);
                }

                if(_this.hasClass('oo-slider-prev')) {
                    _html.find('.oo-news-box-item').fadeOut();

                    if(_index == 0) {
                        _index = _maxItems;
                    } else {
                        _index--;
                    }

                    _html.find('.oo-news-box-item').eq(_index).fadeIn();
                } else {
                    _html.find('.oo-news-box-item').fadeOut();

                    if(_index == _maxItems) {
                        _index = 0;
                    } else {
                        _index++;
                    }

                    _html.find('.oo-news-box-item').eq(_index).fadeIn();
                }

                _html.find('.col-news .oo-header-box-controls small').html((_index + 1));
             });

             _autoPage = setInterval(function() { _html.find('.oo-slider-next').click() }, 4000);
         },

         getCitySuggestions: function(_html) {
            var _target = _html.find('.oo-weather-box-edit-results');
     		var _action = _html.find('[name="weatherCity"]');
     		var _autoComplete = '';
     		var _allowedKeyCodes = [38, 40, 13, 8];

     		_action.keyup(function(e) {

     			if(_allowedKeyCodes.indexOf(e.keyCode) == -1) {

     				var autoComplete = setTimeout(function() {

     					if(_action.val() != "" && _action.val().length > 3) {

     					$.ajax({
     						url: '/strikedata/',
     						type: 'GET',
     						dataType: 'JSON',
     						data: {loadProxy: 1, input: encodeURIComponent(_action.val())},
     						beforeSend: function() {
     							_html.find('.oo-weather-box-edit-inputs span').show();
     						},
     						success: function(json) {

                                _html.find('.oo-weather-box-edit-inputs span').hide();
     							_target.find('a').remove();

                                if(json.predictions.length) {
                                    _target.fadeIn();
                                }

     							$.each(json.predictions, function(i, pred) {

                                    if(pred.terms[2]) {
                                        var _htmlData = $('<a data-city="'+pred.terms[0].value+'" data-country="'+pred.terms[1].value+','+pred.terms[2].value+'">'+pred.terms[0].value+', '+pred.terms[1].value+'</a>');
                                    } else {
                                        var _htmlData = $('<a data-city="'+pred.terms[0].value+'" data-country="'+pred.terms[1].value+'">'+pred.terms[0].value+', '+pred.terms[1].value+'</a>');
                                    }

                                    _target.append(_htmlData);

                                });

     						}
     					});

     					} else {
     						_target.hide();
     					}

     					_index = 0;

     				}, 100);

     			}
     		});

        },

        useCitySuggestions: function(_html) {
            var _modal = _html.find('.oo-weather-box-edit');
            var _overlay = _html.find('.modal-overlay');

            $(document).on('click.suggestion', '.oo-weather-box-edit-results a', function() {

                var _this = $(this);
                _modal.fadeOut();
                _overlay.fadeOut();

                _html.find('.col-weather .oo-header-title-container .oo-header-title').html(_this.attr('data-city'));
                Cookies.set('weatherScrollCity', _this.attr('data-city')+','+_this.attr('data-country'), { expires: 365 });

                onweerOnline.callable.loadWeatherScroll(_html);
                onweerOnline.callable.loadFlashes(_html);
            });
        },

        closeWeatherEditBox: function(_html) {
            var _action = _html.find('.oo-weather-box-edit-close');

            _action.click(function() {
                var _this = $(this);
                var _modal = _this.parent();
                var _overlay = _html.find('.modal-overlay');

                _overlay.fadeOut('fast');
                _modal.fadeOut('fast');
            });
        },

        closeNotificationEditBox: function(_html) {
            var _action = _html.find('.oo-notification-box-edit-close');

            _action.click(function() {
                var _this = $(this);
                var _modal = _this.parent();
                var _overlay = _html.find('.modal-overlay');

                _overlay.fadeOut('fast');
                _modal.fadeOut('fast');
            });
        },

        showWeatherEditBox: function(_html) {
            var _action = _html.find('.oo-edit-location');
            _action.click(function() {
                var _this = $(this);
                var _modal = _html.find('.oo-weather-box-edit');
                var _overlay = _html.find('.modal-overlay');

                _overlay.fadeIn('fast');
                _modal.fadeIn('fast');

                _modal.find('.oo-weather-box-edit-results').hide();
                _modal.find('.oo-weather-box-edit-results a').remove();
                _modal.find('input').val('');
            });
        },

        showNotificationEditBox: function(_html) {
            var _action = _html.find('.oo-edit-notifications');
            _action.click(function() {
                var _this = $(this);
                var _modal = _html.find('.oo-notification-box-edit');
                var _overlay = _html.find('.modal-overlay');

                _overlay.fadeIn('fast');
                _modal.fadeIn('fast');
            });
        },

        handleNotificationEdit: function(_html) {
            var _action = _html.find('.oo-notification-box-edit input[type="checkbox"]');

            _action.click(function() {
                var _options = [];
                var _checkedOptions = _html.find('.oo-notification-box-edit input[type="checkbox"]:checked');

                _checkedOptions.each(function() {
                    var _this = $(this);
                    _options.push(_this.attr('value'));
                });

                Cookies.set('allowedNotificationTypes', _options.join(','), { expires: 365 });
            });
        },

        loadNotificationStates: function(_html) {
            var _modal = _html.find('.oo-notification-box-edit');
            if(Cookies.get('allowedNotificationTypes') || Cookies.get('allowedNotificationTypes') == "") {
                var _options = Cookies.get('allowedNotificationTypes').split(',');
                var _targets = _html.find('.oo-notification-box-edit input[type="checkbox"]');

                _targets.each(function() {
                    var _this = $(this);
                    if(_options.length) {

                        if(_options.indexOf(_this.attr('value')) > -1) {
                            _this.attr('checked', 'checked');
                        } else {
                            _this.removeAttr('checked');
                        }
                    } else {
                        _this.removeAttr('checked');
                    }
                });
            }
        },

        expandNotificationBox: function(_html) {
            var _action = _html.find('.oo-expand-notifications');
            _action.click(function() {
                var _htmlData = _html.find('.oo-livefeed-box .liveticker .notification').clone();
                var _modal = _html.find('.oo-expanded-notification-box');
                var _target = _modal.find('[data-live-feed-container]');
                var _overlay = _html.find('.modal-overlay');

                _target.empty();

                _target.append(_htmlData);
                _modal.fadeIn('fast');
                _overlay.fadeIn('fast');
            });
        },

        closeExpandedNotificationBox: function(_html) {
            var _action = _html.find('.oo-expanded-notification-box-close');

            _action.click(function() {
                var _this = $(this);
                var _modal = _this.parent();
                var _overlay = _html.find('.modal-overlay');

                _overlay.fadeOut('fast');
                _modal.fadeOut('fast');
            });
        },

        setWeatherScrollTitle: function(_html) {
            if(!Cookies.get('weatherScrollCity')) {
                window.countryCode = 'De Bilt,Netherlands';
            } else {
                window.countryCode = Cookies.get('weatherScrollCity');
            }

            var _cityData = window.countryCode.split(',');
            _html.find('.col-weather .oo-header-title').html(_cityData[0]);
        },

        loadWeatherScroll: function(_html) {
            if(_html.find('.oo-current-condition').length) {

                if(!Cookies.get('weatherScrollCity')) {
                    window.countryCode = 'De Bilt,Netherlands';
                } else {
                    window.countryCode = Cookies.get('weatherScrollCity');
                }

                $.ajax({
                    url: 'https://api.openweathermap.org/data/2.5/weather?q='+window.countryCode+'&units=metric&appid=539a962ccb244cacdcbe381d6554b39c',
                    type: 'GET',
                    success: function(report) {

                        _html.find('.oo-current-condition-visual').attr('class', '').addClass('oo-current-condition-visual icon-'+report.weather[0].icon);
                        _html.find('.oo-current-condition').attr('class', '').addClass('oo-header-box oo-weather-box oo-current-condition oo-current-condition-data icon-'+report.weather[0].icon);

                        setTimeout(function() { _html.find('.oo-weather-box .oo-current-condition-visual').css('background-position', '-2050px');}, 300);

                        _html.find('.low').html(Math.floor(report.main.temp_min)+'&deg;');
                        _html.find('.high').html(Math.ceil(report.main.temp_max)+'&deg;');
                        _html.find('.oo-current-condition-data h4').html(window.weathercondition[report.weather[0].icon]);

                        //Wind
                        _html.find('.oo-data-wind').html('<small></small>'+onweerOnline.stashed.getWindSpeed(report.wind.speed)+' / ' +onweerOnline.stashed.getWindDirection(report.wind.deg));

                        //Precepetation
                        var rainAmount;
                        if(report.rain) {
                            if(report.rain["3h"]) {
                               rainAmount = Math.ceil(report.rain["3h"]);
                            }

                            else if(report.rain["1h"]) {
                                rainAmount = Math.ceil(report.rain["1h"]);
                            }
                        }

                        else if(report.snow) {
                            if(report.snow["3h"]) {
                               rainAmount = Math.ceil(report.snow["3h"]);
                            }

                            else if(report.snow["1h"]) {
                                rainAmount = Math.ceil(report.snow["1h"]);
                            }
                        }

                        else if(!report.snow && !report.rain) {
                            rainAmount = 0;
                        }

                        $('.oo-data-precep').html('<small></small>'+rainAmount+' mm');
                        $('.oo-data-pressure').html('<small></small>'+report.main.pressure+' hPa');
                        $('.oo-current-condition, .oo-current-condition-visual').fadeIn();

                    }
                });
            }
        },

        loadFlashes: function(_html) {
            var _noFlashes = 'Geen onweer in de buurt';
            var _flashesDetected = '<strong>%%STRIKES%%</strong>&nbsp; ontladingen <10 km.';
            var _dateTime = new Date();

            if(!Cookies.get('allowFlashReload') || parseInt(Cookies.get('allowFlashReload')) < _dateTime.getTime()) {

                $.ajax({
                    url: 'https://www.onweer-online.nl/strikedata/',
                    type: 'GET',
                    data: {loadRadius: 1, city: window.countryCode},
                    dataType: 'JSON',
                    success: function(strikes) {

                        var _target = _html.find('.oo-flash');
                        if(strikes.count > 0) {
                            _target.html(_flashesDetected.replace('%%STRIKES%%', strikes.count));
                        } else {
                            _target.html(_noFlashes);
                        }

                        Cookies.set('lastFlashAmount', strikes.count, { expires: 365 });
                    }
                });

                Cookies.set('allowFlashReload', (_dateTime.getTime() + 600000), { expires: 365 });

            } else {
                if(Cookies.get('lastFlashAmount')) {
                    _strikeCount = Cookies.get('lastFlashAmount');
                    var _target = _html.find('.oo-flash');
                    if(_strikeCount > 0) {
                        _target.html(_flashesDetected.replace('%%STRIKES%%', _strikeCount));
                    } else {
                        _target.html(_noFlashes);
                    }
                }
            }

            setInterval(function() { onweerOnline.callable.loadFlashes(_html) }, ((1000 * 60) * 10));
        },

        setViewPortWidth: function(_html) {
            var _target = _html.find('[name="viewport"]');
            if(_html.find('#block_c0b988106b24e51f4c232e17b15c2209').length || _html.find('[href*="baseadmin.css"]').length) {
                if($(window).width() < 700) {
                    _target.attr('content', 'width=414');
                } else {
                    _target.attr('content', 'width=device-width');
                }
            }
        },
     },

     stashed: {

         showLoginDialog: function(_html) {

             var _modal = $('<div class="reporting-overlay"><div class="reporting-box"><span>Inloggen <a>Sluiten</a></span><small>Om deze actie uit te kunnen voeren moet je inloggen op OnweerOnline. Heb je nog geen account? Je kunt er gratis één <a style="color: #fdad2a;" href="/forum/register/">aanmaken</a></small><form method="POST" action="/forum/handle-login/"><input style="height: 40px; width: 100%; margin-bottom: 20px; text-indent: 15px;" type="text" name="username" placeholder="Gebruikersnaam"><input style="height: 40px; width: 100%; text-indent: 15px;" type="password" name="password" placeholder="Wachtwoord"></form><a href="" class="button dialog-login" target="_blank">INLOGGEN</a></div></div>');

             _html.find('body').append(_modal);
         },

         getWindSpeed: function(iSpeed) {
             var sBft;

             if(iSpeed > 0.2 && iSpeed < 1.6) {
                 sBft = 1;
             }

             else if(iSpeed > 1.5 && iSpeed < 3.4) {
                 sBft = 2;
             }

             else if(iSpeed > 3.3 && iSpeed < 5.5) {
                 sBft = 3;
             }

             else if(iSpeed > 5.4 && iSpeed < 8.0) {
                 sBft = 4;
             }

             else if(iSpeed > 7.9 && iSpeed < 10.8) {
                 sBft = 5;
             }

             else if(iSpeed > 10.7 && iSpeed < 13.9) {
                 sBft = 6;
             }

             else if(iSpeed > 13.8 && iSpeed < 17.2) {
                 sBft = 7;
             }

             else if(iSpeed > 17.1 && iSpeed < 20.8) {
                 sBft = 8;
             }

             else if(iSpeed > 20.7 && iSpeed < 24.5) {
                 sBft = 9;
             }

             else if(iSpeed > 24.4 && iSpeed < 28.5) {
                 sBft = 10;
             }

             else if(iSpeed > 28.4 && iSpeed < 32.7) {
                 sBft = 11;
             }

             else if(iSpeed > 32.7) {
                 sBft = 12;
             }

             return sBft;
         },

         getWindDirection: function(iDirection) {
            if(iDirection>11.25 && iDirection<33.75) {
                return "NNO";
            } else if (iDirection>33.75 && iDirection<56.25) {
                return "ONO";
            } else if (iDirection>56.25 && iDirection<78.75) {
                return "O";
            } else if (iDirection>78.75 && iDirection<101.25) {
                return "OZO";
            } else if (iDirection>101.25 && iDirection<123.75) {
                return "OZO";
            } else if (iDirection>123.75 && iDirection<146.25) {
                return "ZO";
            } else if (iDirection>146.25 && iDirection<168.75) {
                return "ZZO";
            } else if (iDirection>168.75 && iDirection<191.25) {
                return "Z";
            } else if (iDirection>191.25 && iDirection<213.75) {
                return "ZZW";
            } else if (iDirection>213.75 && iDirection<236.25) {
                return "ZW";
            } else if (iDirection>236.25 && iDirection<258.75) {
                return "WZW";
            } else if (iDirection>258.75 && iDirection<281.25) {
                return "W";
            } else if (iDirection>281.25 && iDirection<303.75) {
                return "WNW";
            } else if (iDirection>303.75 && iDirection<326.25) {
                return "NW";
            } else if (iDirection>326.25 && iDirection<348.75) {
                return "NNW";
            } else {
                return "N";
            }
        }
     },

     init: function() {
         var _html = $('html');

         $.each(this['callable'], function(i, func) {
 			// console.log(func);
 			func(_html);
 		 });
     }
 }

 $(document).ready(function() {
     onweerOnline.init();
 });

 /* BRS @ 13 04 2017 - Move functions to be used globally */

function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};

function downloadUrl(url, callback) {
 var status = -1;
 var request = createXmlHttpRequest();
 if (!request) {
   return false;
 }

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     try {
       status = request.status;
     } catch (e) {
       // Usually indicates request timed out in FF.
     }
     if ((status == 200) || (status == 0)) {
       callback(request.responseText, request.status);
       request.onreadystatechange = function() {};
     }
   }
 }
 request.open('GET', url, true);
 try {
   request.send(null);
 } catch (e) {
   changeStatus(e);
 }
};

function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

 $(document).ready(function() {


	 /**
	  * Cookie Notice
	  */

	 // if(Cookies.get('noticeDismissed') !== "true" || !Cookies.get('noticeDismissed')) {
     //
	 // 	$('body').addClass('cookie-warning-open');
	 // 	$('<div class="oo-cookie-notice"><div class="oo-cookie-notice-inner"><p>Onweer Online maakt gebruik van eigen cookies en die van derden om zo een betere service te kunnen verlenen. Als je gebruik maakt van onze website ga je akkoord met het plaatsen van onze functionele en analytische cookies.</p> <a class="oo-cookie-dismiss button">Akkoord</a></div></div>').insertBefore('.oo-top-bar');
     //
	 // }
     //
     //
	 // $(document).on('click.allowCookies', '.oo-cookie-dismiss', function(e) {
		// e.preventDefault();
     //
		// Cookies.set('noticeDismissed','true', { expires: 365 });
		// $('body').removeClass('cookie-warning-open').find('.oo-cookie-notice').hide();
     //
	 // });


	 /** Set Slider for Radar **/

	 $('.doppler-index-control').slider({
		max: 11,
		step: 1,
		slide: function(event, ui) {
			if(!$('.doppler-pause').hasClass('paused')) {
				$('.doppler-pause').click();
			}

	        $('.dopplerradar img').attr('src', 'https://onweer-online.nl/tools/cache/'+$('.dopplerradar img').attr('data-prefix')+ui.value+'.gif?'+Math.random()).attr('data-radindex', ui.value);
	    }
	 });

	 var dopplerRadar = setInterval(function() { animateRadar() }, 1000);

	 function animateRadar() {
	 	var index = $('.dopplerradar img').attr('data-radindex');
	 	index++;

	 	if(index == 12) {
			index = 0;
		}

	 	$('.dopplerradar img').attr('src', 'https://onweer-online.nl/tools/cache/'+$('.dopplerradar img').attr('data-prefix')+index+'.gif?'+Math.random()).attr('data-radindex', index);
	 	$('.doppler-index-control').slider('value', index);

	 }

	 function pauseRadar() {
		 clearInterval(dopplerRadar)
	 }

	 $('.doppler-pause').click(function(e) {
		 e.preventDefault();

		 if(!$(this).hasClass('paused')) {
			 pauseRadar();
			 $(this).addClass('paused').html('&#9658;');
		 } else {
			 dopplerRadar = setInterval(function() { animateRadar() }, 1000);
			 $(this).removeClass('paused').html('&#9612;&nbsp;&#9612;');
		 }
	 });

     if($(window).width() < 700) {
         $('.mainmenu').click(function() {
             var _this = $(this);
             _this.find('> li').fadeToggle('fast');
         });
     }

 });
