﻿var sliderIds = new Array();
var previousWidth=-1;
var chart;
var subData;

jQuery(function () {

    initLightBoxModalPopUp();
    jQuery('.promoBox').each(function (index, elem) {
        var img = new Image();
        img.src = jQuery(elem).attr('title');

        jQuery(img).load(function () {
            var width = img.width;
            var height = img.height;
            jQuery(elem).attr('title', '');
            jQuery(elem).removeClass('promoLoading');
            var style = jQuery(elem).attr('style');
            style = "background-image: url('" + this.src + "');";
            if (jQuery(elem).hasClass("widgetpromobox")) {
                style += " width:" + width + "px;height:" + height + "px;display:block;max-width:100%;";
                var margintop = height - 35;
                jQuery(elem).find(".widgetpromotitle").attr("style", "margin-top:" + margintop + "px");
            }
            jQuery(elem).attr('style', style);
        })
    });
});

/************************  [ Modal Pop Up Logic - Start ] ********************/
function initLightBoxModalPopUp() {
	//var genericLightBoxId = "";
	var header = "";
	var body = "";

	jQuery('.light-box-content-no-style').find('a').click(function () {
		CreatePopup(this);
		return false;
	});

	jQuery('.sliderVideo').click(function () {
		CreatePopup(this);
		return false;
	});

  	jQuery('.light-box-content-no-style').find('a').showLightBox(genericLightBoxId);
	jQuery('.sliderVideo').showLightBox(genericLightBoxId);
}

function createChart(chartData) {
     
    if (chartData.length > 0) {

        var arrayVariables = chartData.split('|');
                
        subData = eval('(' + arrayVariables[7] + ')');
        var categories = eval('(' + arrayVariables[8] + ')');
        var title = eval('(' + arrayVariables[0] + ')');
        var subtitle = eval('(' + arrayVariables[1] + ')');
        var xAxis = eval('(' + arrayVariables[2] + ')');
        var yAxis = eval('(' + arrayVariables[3] + ')');
        var plotOptions = eval('(' + arrayVariables[4] + ')');
        var series = eval('(' + arrayVariables[5] + ')');
        var tooltip = eval('(' + arrayVariables[6] + ')');
   
        chart = new Highcharts.Chart({
                chart: {
                    renderTo: 'chart-container',
                    defaultSeriesType: 'column'
                },
                title: title,
                subtitle:subtitle,
                xAxis: xAxis,
                yAxis: yAxis,
                legend: {
                    enabled: false                  
                },
                credits: {
                    enabled: false
                },
                plotOptions: plotOptions,
                tooltip: tooltip,
                series: series
            });
    }
}

function setChart(name, categories, data, color, title) {
      chart.xAxis[0].setCategories(categories);
      chart.series[0].remove();
      chart.setTitle({text:title});
      chart.addSeries({
         name: name,
         data: data,
         color: color || '#4572a7'
      });
}

function CreatePopup(item) {
	var urlObj = ParseUrl(jQuery(item).attr('href'));

	if (urlObj.host == document.domain) {

	    jQuery(genericLightBoxId + ' .light-box-header span').html('');
	    jQuery.get(jQuery(item).attr('href'), function (result) {

	        jQuery('.form-container').css('background-image', '');
	        jQuery('.form-container').addClass('form-container-padding');
	        jQuery(genericLightBoxId + ' .light-box-header span').html(jQuery(result).find("#spanheaderForLB").html());
	        jQuery(genericLightBoxId + ' .light-box-content .form-container').html(jQuery(result).find("#formContainerForLB").html());

	    });
	    jQuery(genericLightBoxId + ' .light-box-header span').data('href', jQuery(item).attr('href'));

	    PauseAllSliders();

	} else if (urlObj.host == "www.youtube.com" && urlObj.params['v'] != null) {

	    var videoFrame = document.createElement('iframe');
	    jQuery('.form-container').removeClass('form-container-padding');
	    videoFrame.setAttribute('id', 'frameForYouTube');
	    videoFrame.setAttribute('src', 'http://www.youtube.com/embed/' + urlObj.params['v'] + '?html5=1&autoplay=1');
	    videoFrame.setAttribute('frameborder', '0');
	    videoFrame.setAttribute('width', '100%');
	    videoFrame.setAttribute('height', '315px');

	    var modalFrame = document.createElement('div');
	    modalFrame.setAttribute('id', 'modalVideoFrame');

	    modalFrame.appendChild(videoFrame);

	    jQuery(genericLightBoxId + ' .light-box-header span').html('');
	    jQuery(genericLightBoxId + ' .light-box-content .form-container').html('');
	    jQuery(genericLightBoxId + ' .light-box-content .form-container').html(modalFrame);
	    jQuery('.form-container').css('background-image', '');
	    PauseAllSliders();

	} else { }
}

function PauseAllSliders() {
	jQuery.each(sliderIds, function (index, value) {
		jQuery('#' + value).data('nivoslider').stop();
	});
}

function UnPauseAllSliders() {
	jQuery.each(sliderIds, function (index, value) {
		jQuery('#' + value).data('nivoslider').start();
	});
}
/************************  [ Modal Pop Up Logic - End ] ********************/

/************************  [ Light box plugin - Start ] ********************/
(function ($) {
	jQuery.fn.showLightBox = function (id) {
		var lightBoxbtn = jQuery(this);
		var lightBoxContainer = jQuery(id + ' .light-box').find('.light-box-container');
		var lightBoxContent;

		jQuery(lightBoxbtn).click(function () {
           
			jQuery(id + ' .light-box').fadeIn(function(){var data = jQuery(this).find("#chart-data").html(); if(data){createChart(data)};});
			jQuery('.form-container').css('background', '#fff url(/App_Themes/MightyRiverPower/images/image_slider/loading.gif) no-repeat center center');
			document.documentElement.style.overflow = 'hidden';
            
			return false;
		});

		jQuery(id + ' .light-box .close-but').click(function () {
			jQuery(id + ' .light-box').fadeOut(function(){chart && chart.destroy();chart = null; });
			document.documentElement.style.overflow = 'auto';
			try {
				if (jQuery('#modalVideoFrame').length != 0) {
					jQuery('.form-container').css('background', '#fff url(/App_Themes/MightyRiverPower/images/image_slider/loading.gif) no-repeat center center');
					jQuery('#modalVideoFrame').empty();
				}
				UnPauseAllSliders();
			} catch (ex) { }
			return false;
		});
	}
})(jQuery);

/************************  [ Light box plugin - End ] ********************/

/************************  [ URL Parser - Start ] ********************/

function ParseUrl(url) {
	var a = document.createElement('a');
	a.href = url;
	var hostname = a.hostname;
	if (url.charAt(0) == '/') {
		hostname = document.domain;
	}
	return {
		source: url,
		protocol: a.protocol.replace(':', ''),
		host: hostname,
		port: a.port,
		query: a.search,
		params: (function () {
			var ret = {},
                seg = a.search.replace(/^\?/, '').split('&'),
                len = seg.length, i = 0, s;
			for (; i < len; i++) {
				if (!seg[i]) { continue; }
				s = seg[i].split('=');
				ret[s[0]] = s[1];
			}
			return ret;
		})(),
		file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
		hash: a.hash.replace('#', ''),
		path: a.pathname.replace(/^([^\/])/, '/$1'),
		relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
		segments: a.pathname.replace(/^\//, '').split('/')
	};
}

/************************  [ URL Parser - End ] ********************/

/************************  [ Document.Ready Call ] ********************/
(function ($, sr) {

    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced() {
            var widthval = jQuery(".slider-wrapper").width()
           if(previousWidth!=widthval)
           {
                previousWidth=widthval;
                PauseAllSliders();
                var obj = this, args = arguments;
                function delayed() {
                    if (!execAsap)
                        func.apply(obj, args);
                    timeout = null;
                };

                if (timeout)
                    clearTimeout(timeout);
                else if (execAsap)
                    func.apply(obj, args);

                timeout = setTimeout(delayed, threshold || 100);
            }
            else
            {
                previousWidth=-1;
            }
        };
    }
    // smartresize 
    jQuery.fn[sr] = function (fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery, 'smartresize');


(function ($, sr) {

    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced() {        
            var obj = this, args = arguments;
            function delayed() {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
            };

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 100);          
        };
    }
    // smartresize 
    jQuery.fn[sr] = function (fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery, 'smartresizeforlightbox');


jQuery(document).ready(function () {

    jQuery(".leftM_CMSListMenuLinkHighlighted").hover(function () { jQuery(this).css("color", "#006dbd") }, function () { jQuery(this).css("color", "black") });
    if (jQuery(".leftBoxCSSlist").length > 0 && jQuery(".leftBoxCSSlist").children().length <= 1) { jQuery(".leftBoxCSSlist").hide(); }
    if (jQuery(".zoneHero") && jQuery(".zoneHero").children().length <= 0) { jQuery(".zoneHero").hide(); }
});

function OpenWindow(url){
    var h=screen.availHeight, w=screen.availWidth;    
    var win = window.open(url, '', 'statusbar=yes,menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes,top=0,left=0,width=' + w + ',height=' + h);
    win.resizeTo(w,h);
    win.focus();
    return false;
}

